代码之家  ›  专栏  ›  技术社区  ›  user944513

如何在React JS中接收更新的道具?

  •  0
  • user944513  · 技术社区  · 7 年前

    你能告诉我如何在React JS中接收更新的道具吗?我知道 componentWillReceiveProps unsafe 我试着用 getDerivedStateFromProps 但不工作

    这是我的密码 https://codesandbox.io/s/rm30zoonk4

    两秒钟后,我正在更新我的状态 props

    Expected output after two second

    abcsssss

    static getDerivedStateFromProps(nextProps, prevState) {
        if (nextProps.src !== "") {
          return { src: nextProps.src };
        } else return null;
      }
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   CoderXYZ    7 年前

    componentDidUpdate(prevProps) {
      if (prevProps.src !== this.props.src) {
        this.test()
      }
    }
    

        2
  •  0
  •   wdm    7 年前

    componentDidUpdate

    https://reactjs.org/docs/react-component.html#componentdidupdate

    class Hello extends Component {
        state = {
            name: ""
        }
        componentDidUpdate(prevProps) {
            if (this.props.src !== prevProps.src) {
                this.setState({name: this.props.src + 'ssss'});
            }
        }
        render() {
            return <div>{this.state.name}</div>;
        }
    }