首页 > 解决方案 > 在 ReactJS 中正确更新孩子的状态

问题描述

我发现我的状态没有正确更新。如果您看到下面的代码console.log(this.props.clickedImage)给出了我期望的值,但console.log(this.state.items);不是。

我正在使用componentWillReceiveProps()它来更新它,但我不确定这是否是好方法。最好的方法是什么?

家长:

constructor(props){
    super(props);
    // set the state to handle which of the panes displays the information you want
    this.handleChildClick = this.handleChildClick.bind(this),
    this.state= {
        clickedItem: 'none',
    };
}

handleChildClick(src) {
    this.setState({ clickedItem: src });
}

render() {
    return (
        <div className="ao">
                <CharacterForm clickedImage={this.state.clickedItem}/>
                <SearchForm image_clicked={this.handleChildClick}/>

        </div>

    );
}

孩子甲:

    constructor(props) {
        super(props);
        this.state = {
            items: [
                { name: "one", divStyle: this.props.clickedImage},
                { name: "two", divStyle: this.props.clickedImage},
                { name: "three", divStyle: this.props.clickedImage},
            ]
        };
    }

    componentWillReceiveProps(nextProps){
        if(nextProps.itemsLeft !==this.props.clickedImage){
            this.setState({

            })
        }
    }


    render() {
        console.log(this.props.clickedImage); 
        console.log(this.state.items);

        return this.state.itemsRight.map(item => (
            <FrameCharacter key={item.name} item={item} />
        ));
    }

孩子乙:

render() {
    <img src="../images/misc/eq.png" onClick={() => image_clicked(eq.image)}/>
}

标签: reactjs

解决方案


componentWillReceiveProps已弃用。getDerivedStateFromProps这种情况就是引入钩子的确切原因。它允许从 props 派生状态,包括最初在构造函数中收到的那些:

static getDerivedStateFromProps(props, state) {
  return {
    items: [
      { name: "one", divStyle: props.clickedImage }
      ...
    ];
  }
}

请注意,这propsgetDerivedStateFromProps. 如果需要访问以前的clickedImage道具来完全替换componentWillReceivePropsclickedImage也可以存储到状态中。


推荐阅读