我有两个组件 Main 和 Child
export default class Main extends Component {
render() {
return (
<View>
<Child item={this.state.selectedItem} />
</View>
)
}
}
export default class Child extends Component {
state = {
newItem: null
};
organiseProductOptions() {
const { item } = this.props;
Async Request with item.ID... {
setState({ newItem: response })
}
}
componentDidMount() {
this.organiseProductOptions();
}
render() {
return (
<View>
<Text>{this.state.newItem.name}</Text>
</View>
)
}
}
通常,this.organiseProductOptions(( 函数在 componentDidMount(( 初始状态下工作。但是,当我尝试重新渲染 Child 时,render(( 方法正在工作,但 componentDidMount(( 不起作用。
当我在主组件中设置状态选择项目属性时,如何在子组件中触发 this.organiseProductOptions(( 函数?
请注意,子组件有自己的状态。
由于Child
只挂载一次,因此您可以检查Child
的道具何时更改并执行您的请求。加
componentDidUpdate(prevProps) {
if (prevProps.item !== this.props.item) { // 'item' is changed
this.organiseProductOptions();
}
}
当道具更改但不会重新挂载时,子组件会重新渲染。因此,当孩子挂载时,它会将 newItem 设置为 this.props.item,但之后 newItem 将永远不会更改。
标准做法是只在子组件中的任何位置使用 this.props.item。