将传递函数反应给子父对象而不是重新渲染

React pass function to child parent not re rendering

我有以下功能:

update() {
    this.currentItem = [];
    //...Populate currentItem

    this.setState({
      currentItem
    });
  }

这样在页面上呈现;

render() {
   const { currentItem } = this.state;
   return {currentItem}
}

然后我将此函数传递给子组件,如下所示:

<Component
   update={this.update.bind(this)}
/>

然后在我的子组件中这样调用它:

let { update } = this.props;
if (typeof update === "function")
  update();

问题是更新功能没有重新呈现我在父页面上更新的内容。据我了解,每当调用 setState 时,也会调用 render 。 render() 似乎确实被调用了,但它似乎没有显示更新后的值 - 为什么会这样,我该如何解决它?

我想这可能是因为它来自子组件?

我试过 forceUpdate,但它也没有重新渲染组件 - 我错过了什么?

我只是在猜测,但我认为您在构造函数中设置了子组件的初始值以及您希望它反映的值指向它自己的状态而不是父状态

我需要先将状态设置为loading,然后当我将其设置为loading = false时,它会重新呈现该页面

this.setState({
      loading:true
    });    

//...Do the work

this.setState({
      loading:false
    });    

尽量避免 this.forceUpdate() 因为这不会触发 shouldComponentUpdate () 这是 React 中组件的性能挂钩。因为,我看到你正在将你的状态传递给子组件并试图从那里更新父状态对象,这是违法的。您应该在父组件中创建一个方法并将该方法作为 prop 传递给子组件。它应该是这样的

constructor(props) {
    super(props);
    this.state = { loading: false };
    this.update = this.update.bind(this);
}
update(newState) {
    this.setState({loading: newState })
}
render() {
    return <ChildComponent update={this.update} />
}