为什么在下面的伪代码示例中,当容器更改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仍然显示旧值。


当前回答

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

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

其他回答

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

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

根据React的理念,组件不能改变它的道具。它们应该从父进程接收,并且应该是不可变的。只有父节点可以更改其子节点的道具。

关于国家和道具的解释很好

另外,阅读这篇文章为什么我不能在react.js中更新道具?

我有同样的问题的重新渲染对象道具,如果道具是一个对象JSON.stringify(obj),并将其设置为功能组件的关键。为react钩子设置一个id键对我来说并不适用。奇怪的是,要更新组件,你必须在键上包含所有对象属性并将其连接到那里。

function Child(props) {
  const [thing, setThing] = useState(props.something)
  
  return (
   <>
     <div>{thing.a}</div>
     <div>{thing.b}</div>
   </>
  )
}

...

function Caller() {
   const thing = [{a: 1, b: 2}, {a: 3, b: 4}]
   thing.map(t => (
     <Child key={JSON.stringify(t)} something={thing} />
   ))
}

现在,任何时候thing对象在运行时改变了它的值,子组件将正确地重新呈现它。

你应该使用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>
        }
    }
}

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

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

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

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

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