使用道具初始化状态使我的状态未定义
Init state with a props make my state undefined
我很快创建了这个 sandbox 来更容易地解释我的问题。
我希望在单击我的 clickableItem
时,simplePopOver
组件的输入值从 clickableItem
组件的状态中获取值。
为此,我使用道具从 simplePopOver
初始化状态,但问题是状态始终等于初始值 'initialisation'
而道具具有良好的价值(检查 console.log()
).你有想法吗 ?是异步问题吗?
我不认为我的解释很清楚,但如果你检查沙箱它会更清楚:)
状态可点击元素文本
未声明
使用this.state.textInInput
您需要实施 getDerivedStateFromProps
以根据 SimplePopover
组件中道具的变化更新状态
static getDerivedStateFromProps(props, state) {
console.log(props);
if (props.clickableElementText !== state.prevClickableElementText) {
return {
prevClickableElementText: props.clickableElementText,
textInInput: props.clickableElementText,
}
}
return {
prevClickableElementText: props.clickableElementText
}
}
我很快创建了这个 sandbox 来更容易地解释我的问题。
我希望在单击我的 clickableItem
时,simplePopOver
组件的输入值从 clickableItem
组件的状态中获取值。
为此,我使用道具从 simplePopOver
初始化状态,但问题是状态始终等于初始值 'initialisation'
而道具具有良好的价值(检查 console.log()
).你有想法吗 ?是异步问题吗?
我不认为我的解释很清楚,但如果你检查沙箱它会更清楚:)
状态可点击元素文本
未声明
使用this.state.textInInput
您需要实施 getDerivedStateFromProps
以根据 SimplePopover
组件中道具的变化更新状态
static getDerivedStateFromProps(props, state) {
console.log(props);
if (props.clickableElementText !== state.prevClickableElementText) {
return {
prevClickableElementText: props.clickableElementText,
textInInput: props.clickableElementText,
}
}
return {
prevClickableElementText: props.clickableElementText
}
}