相关疑难解决方法(0)

何时使用componentWillReceiveProps生命周期方法?

我是React/Redux的新手并且遇到状态问题.

TrajectContainer.jsx

class TrajectContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            trajects: props.trajects,
            onClick: props.onClick
        };
    }

    componentWillReceiveProps(nextProps) {
        console.log('componentWillReceiveProps', nextProps);
        this.setState(nextProps);
    }

    render() {
        // When the componentWillReceiveProps is not present, the this.state will hold the old state
        console.log('rerender', this.state);
        return (<div className="col-md-6">
            <h2>Trajects</h2>
            <button className="btn btn-primary" onClick={this.state.onClick}>Add new Traject</button>
            {this.state.trajects.map(traject => <Traject traject={traject} key={traject.name}/>)}
        </div>)
    }
}

const mapStateToProps = function (store) {
    console.log('mapToStateProps', store);
    return {
        trajects: store.trajects
    };
};

const mapDispatchToProps = function (dispatch, …
Run Code Online (Sandbox Code Playgroud)

reactjs react-redux

33
推荐指数
3
解决办法
6万
查看次数

每次收到道具时,componentWillRecieveProps都会运行

我正在阅读React facebook的文档,并在那里写道

组件接收新道具时调用.初始渲染不会调用此方法.

但后来在这个链接中,已经解释过,即使道具相同,也会调用此方法,因为道具可以是引用,并且这些引用的数据可能不同.

所以,我的问题是每次收到新道具时都会调用它.

html reactjs

2
推荐指数
1
解决办法
7877
查看次数

标签 统计

reactjs ×2

html ×1

react-redux ×1