我有以下功能:
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,但它也没有重新渲染组件 - 我错过了什么?
最佳答案
尽量避免使用 this.forceUpdate() 因为这不会触发 shouldComponentUpdate() 这是一种性能在 React 中 Hook 您的组件。因为,我看到你正在将你的状态传递给子组件并试图从那里更新父状态对象,这是违法的。您应该在父组件中创建一个方法并将该方法作为 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} />
}
关于javascript - 将传递函数 react 给子父对象而不是重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43500168/