为什么在下面的伪代码示例中,当容器更改foo.bar时,子不重新呈现?

Container {
  handleEvent() {
    this.props.foo.bar = 123
  },

  render() {
    return <Child bar={this.props.foo.bar} />
}

Child {
  render() {
    return <div>{this.props.bar}</div>
  }
}

即使我在修改Container中的值后调用forceUpdate(), Child仍然显示旧值。


当前回答

你应该使用setState函数。如果不是,无论如何使用forceUpdate, state都不会保存您的更改。

Container {
    handleEvent= () => { // use arrow function
        //this.props.foo.bar = 123
        //You should use setState to set value like this:
        this.setState({foo: {bar: 123}});
    };

    render() {
        return <Child bar={this.state.foo.bar} />
    }
    Child {
        render() {
            return <div>{this.props.bar}</div>
        }
    }
}

你的代码似乎无效。我不能测试这段代码。

其他回答

你必须使用动态组件。

在这个代码片段中,我们多次渲染子组件并传递key。

如果我们动态渲染一个组件多次,那么React不会渲染该组件,直到它的键被更改。

如果我们使用setState方法更改检查。它不会反映在子组件中,直到我们改变它的键。我们必须在child的状态上保存它然后相应地将它改为渲染child。

类父扩展组件{ 状态= { 检查:真 } 呈现(){ 回报( < div className =“父”> { [1,2,3].map( N => <div key={N}> <孩子完成= {this.state。检查}/ > < / div > ) } < / div > ); } }

更新子进程以使属性'key'与名称相等。每次键改变时,组件都会重新呈现。

Child {
  render() {
    return <div key={this.props.bar}>{this.props.bar}</div>
  }
}

我的案例涉及在props对象上有多个属性,并且需要在更改其中任何一个时重新渲染Child。 上面提供的解决方案是有效的,但为每个方案添加一个密钥变得乏味和肮脏(想象一下有15个……)如果有人面临这个问题,你可能会发现stringify props对象很有用:

<Child
    key={JSON.stringify(props)}
/>

这样,对props上的每个属性的每次更改都会触发Child组件的重新呈现。

希望这能帮到别人。

因为如果父对象的道具改变了,子对象不会重新渲染,但是如果它的STATE改变了:)

你所展示的是: https://facebook.github.io/react/tips/communicate-between-components.html

它将通过道具将数据从父对象传递到子对象,但没有渲染逻辑。

你需要为父节点设置一些状态,然后在父节点更改状态上重新渲染子节点。 这可能会有所帮助。 https://facebook.github.io/react/tips/expose-component-functions.html

你应该使用setState函数。如果不是,无论如何使用forceUpdate, state都不会保存您的更改。

Container {
    handleEvent= () => { // use arrow function
        //this.props.foo.bar = 123
        //You should use setState to set value like this:
        this.setState({foo: {bar: 123}});
    };

    render() {
        return <Child bar={this.state.foo.bar} />
    }
    Child {
        render() {
            return <div>{this.props.bar}</div>
        }
    }
}

你的代码似乎无效。我不能测试这段代码。