【问题标题】:can't update state with props无法使用道具更新状态
【发布时间】:2020-07-26 13:43:10
【问题描述】:

找到这个:https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#new-lifecycle-getderivedstatefromprops

我很确定这就是我要找的。

我正在尝试在道具更改时更新我的​​状态,以便在我的道具更改时更新视图。

(为什么我所描述的听起来像火箭科学?基本上在尼安德特语中,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


【解决方案1】:

我发现在父级中声明状态并将状态(而不是全局变量)传递给子级就足以让使用 props 的子级始终更新,不需要子级中的任何方法。

这些东西并不明显,应该在文档中解释为 b̶e̶t̶t̶e̶r̶。

【讨论】:

    猜你喜欢
    • 2018-09-06
    • 2020-06-19
    • 2019-06-23
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多