组件没有正确更新视图

时间:2018-01-15 11:40:06

标签: javascript reactjs redux

Render确实被调用了,即使调试器显示temp已正确填充,但似乎没有发生更改(json字符串不会使它成为dom)。我可能遗漏了一些明显的东西。

class ProfileComponent extends Component {

    constructor(props){
        this.props = props;
    }

    componentDidMount(){
        window.mainStore.subscribe(this.render.bind(this))
    }

    render() {
        var temp = JSON.stringify(window.mainStore.getState().profile);
        return (
            <div>
                {temp}
            </div>
        );
    }
}

调试看起来像:

enter image description here

1 个答案:

答案 0 :(得分:1)

似乎第一次'ProfileComponent'呈现我们没有subscribe方法,在componentDidMount之后我们看到正确的结果,让我们尝试添加阻止第一个渲染的状态以返回无效的{temp}:< / p>

class ProfileComponent extends Component {
 constructor(props){
        super(props);
        this.state = { loading: true, temp:''};
    }
 componentDidMount() {     
      window.mainStore.subscribe(); // I don't see all your code but i think here we don't need to bind the render because the component will render after again after changing the state (you can try it both)
      const temp = JSON.stringify(window.mainStore.getState().profile); // better keeping 'window' logic here (especially if our app is SSR) 
      this.setState({loading: false,temp});
    }
 render() {
    const {loading, temp} = this.state;
    if(loading) {return (<div>Loading...</div>)}
    return (
        <div>
            {temp}
        </div>
    );
}
};