React div样式在渲染时不更新

时间:2019-02-04 20:16:22

标签: reactjs

当我在上下文中填充数组时,我正在尝试更新div的背景颜色。在初始渲染时,背景设置与我期望的一样,但是当上下文更新并且将新值推入数组时,我可以看到标签中的长度增加了,但是样式中设置的背景颜色却没有似乎没有更新。

以下代码:

import React, { Component } from 'react';
import { Consumer } from '../../context';

import AlertWindow from './AlertWindow';

class AlertTab extends Component {
    constructor(props){
        super(props);

        this.state = {
            type: props.type,
            active_color: props.active_color
        }
    }

    render() {
        return (
            <Consumer>
                {value => {
                    const { geofence_alarms } = value;
                    const { type, active_color } = this.state;

                    return (
                        <div>
                            <div className='alert-tab' style={{background: (geofence_alarms.length > 0 ? active_color : '#8E8E8E')}}>
                                <h6>{type}</h6>
                                <h6 style={{fontSize:'22pt', float: 'right'}}>{geofence_alarms.length}</h6>
                            </div>
                            <AlertWindow />
                        </div>
                    )
                }}
            </Consumer>
        )
    }
}

export default AlertTab;

从下面的图像中您可以看到 geofence_alerts 数组的长度确实增加了:

geofence_alerts length increasing

我假设这与在React中加载样式的方式有关,但是有人知道我可以实现此目的的正确方法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

简单地说,请勿将this.state用于道具。更新属性时,将发生重新渲染,但不会重新初始化/重新安装组件。由于将道具复制到构造函数中的状态,因此不会调用该状态,并且您的状态将包含安装组件时最初传入的旧道具。在这种情况下,您可以直接从typeactive_colorthis.props

import React, { Component } from 'react';
import { Consumer } from '../../context';

import AlertWindow from './AlertWindow';

class AlertTab extends Component {
    render() {
        return (
            <Consumer>
                {value => {
                    const { geofence_alarms } = value;
                    const { type, active_color } = this.props;

                    return (
                        <div>
                            <div className='alert-tab' style={{background: (geofence_alarms.length > 0 ? active_color : '#8E8E8E')}}>
                                <h6>{type}</h6>
                                <h6 style={{fontSize:'22pt', float: 'right'}}>{geofence_alarms.length}</h6>
                            </div>
                            <AlertWindow />
                        </div>
                    )
                }}
            </Consumer>
        )
    }
}

export default AlertTab;
相关问题