【发布时间】:2020-07-26 13:43:10
【问题描述】:
我很确定这就是我要找的。
我正在尝试在道具更改时更新我的状态,以便在我的道具更改时更新视图。
(为什么我所描述的听起来像火箭科学?基本上在尼安德特语中,Array go to View)
我的数组来自订阅(不是 html.get,它只是一个穷人的商店)。
我订阅了父级并将其作为道具传递,因为显然将其放在同一个组件中不会更新。
我的问题是getDerivedStateFromProps() 在初始化时触发但不是在更新时触发(由于某种原因,初始化值不是从父级传递的值),并且在我点击最终正确控制台后不再触发。登录父级。
另一方面,componentDidUpdate() 根本不会触发。
我有这个:
interface Props {
mything: string
}
interface State {
mything: string
}
class Component extends React.Component<Props, State> {
constructor(props: any) {
super(props);
this.state = { mything: ''}
}
static getDerivedStateFromProps(props: Props, state: State) {
console.log('hi', props);
return {tanks: props.mything}
}
componentDidUpdate(prevProps: Props, prevState: State){
console.log('ho');
if(prevProps.mything !== this.props.mything){
this.setState(state => ({
mything: this.props.mything
}));
}
}
componentWillReceiveProps(nextProps: Props, nextContext: Props): void {
console.log('d')
this.setState(state => ({
mything: this.props.mything
}));
}
render() {
return(
{this.state.mything.map((thing: thingType, index: number) => {
return (
<div key={index} />
</div>
)
})}
)
}
props 已正确传递且可读。我可以成功地对其进行迭代,但是对于显然不是我想做的更新,我想将其复制到状态并对其进行迭代。
因此为什么在上面的代码中我指的是状态的神话而不是道具的神话。
我对使用componentDidUpdate() 或getDerivedStateFromProps() 不感兴趣,我只是认为它们会是我的解决方案,正如您在上面看到的,我尝试componentWillReceiveProps() 的成功率更低,而且我了解到它正在被弃用。有UNSAFE_componentWillReceiveProps(),但光是名字就足以让我明白我会逆流而上。
但就目前而言,我找不到将道具复制到状态的方法。 (当然也会发生在道具更改时)。
【问题讨论】:
标签: reactjs typescript react-props react-component react-state