简体   繁体   English

在传递道具之前反应突变状态

[英]React mutate state before passing props

Is there any way to change state first before passing props from state to its children component in react? 在将prop从状态传递到子组件时,有什么方法可以先更改状态? Here is an example: 这是一个例子:

static getDerivedStateFromProps(nextProps, prevState) {
    let parsedKeyword = queryString.parse(nextProps.location.search).q;

    if (parsedKeyword !== prevState.keyword) {

        return {
            keyword: parsedKeyword,
        }

    }

    return {
        keyword: prevState.keyword,
    };
}

render() {
    return ( 
       <ChildComponent myProps={this.state.keyword} />
    );
}

In my case, I want react to change the keyword state immediately when receiving nextProps before passing props to ChildComponent . 就我而言,我想在将props传递给ChildComponent之前,在接收nextProps时立即做出反应以更改关键字状态。 How can i do it in react? 我该如何反应?

You can modify it before return statement inside getDerivedStateFromProps . 您可以在getDerivedStateFromProps return语句之前修改它。

Alternatively you can manipulate in render, before passing to ChildComponent, it doesn't change the state though. 或者,您可以在渲染中进行操作,但是在传递给ChildComponent之前,它不会更改状态。

render() {
  const modifiedKeyword = this.state.keyword + 'Modified'
  return (
    <ChildComponent myProps={modifiedKeyword}/>
  );

}

I'm assuming you are using the latest version of React (v16.3.2). 我假设您使用的是最新版本的React(v16.3.2)。

The React Blog suggests you should initialize state in your constructor. React Blog建议您应该在构造函数中初始化状态。 According to the React Doc , getDerivedStateFromProps is called after component initialization, and again when new props are received. 根据React Doc的说法, getDerivedStateFromProps在组件初始化之后被调用,并且在收到新的props时再次被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM