简体   繁体   中英

How to update the state in mounting in reactjs

how to update the state after mounting or how to pass the state when moving from one page to another in react.

In My Scenario, by clicking button Add New , it directs to AddNew page, in that clicking on save will redirect to display page, that works. when i move to addnew page In Display multiselect remain same(always en), how to get rendered state after redirecting

class Display extends React.PureComponent{
  constructor(props) {
    super(props);
}
componentWillMount() {
    console.log(this.state.language);
    const defLanguage = this.props.loginData.language; // "en"
    this.setState({ language: defLanguage.split(",") }, () =>
      this.callQueryApiForFetch("ONLOAD")
    );
  }
render(){
               <MultiSelect
                      filterOptions={formatLanguageArray(
                        languageConfig.pvalues
                      )}
                      setSelectedFieldValues={value => {
                        this.setState({ language: value }, () => {
                          this.callQueryApiForFetch("ONLOAD");
                        });
                      }}
                      id="language"
                      itemsSelected={this.state.language}
                      label="Select Language"
                    />

         <button className="page-header-btn icon_btn display-inline">
            <img
              title="edit"
              className="tableImage"
              src={`${process.env.PUBLIC_URL}/assets/icons/ic_addstore.svg`}
            />
            {`Add New`}
          </button>

}

}


class AddNew extends React.Component {

  constructor(props) {
    super(props);

  }
componentWillReceiveProps = () => {
     const defLanguage = this.props.location.state.language;
      this.setState({ language: defLanguage }); 
}
 render(){

           <Link
          to={{
            pathname: "/ui/product-info",
            state: {
              language: this.state.language
            }
          }}
          className="btn btn-themes btn-rounded btn-sec link-sec-btn"
        >
          Save
        </Link>
}

Since you mentioned to redirect to next page , you can also try this.props.history.push("/report") here "/report" is the link you want to redirect to. You can check React-Routing Concept (just a suggestion)

For sending props from parent component to child component your case :

  componentWillReceiveProps(nextProps){
      if(nextProps.someValue!==this.props.someValue){
        //Perform some operation
        this.setState({someState: someValue });
        this.classMethod();
      }
    }

It is a good practice in React to separate state management from component rendering logic. The idea is that you pass fragments of a centralized state to your component hierarchy, from top to bottom, and allow them to use these data in their render method. In this approach you avoid keeping application state within the components.

Whenever a component needs to change the application state, it dispatches a message that is processed by a function called "reducer", and updates the state in the store. The whole concept is based on having a single source of truth for the entire application, and preventing components from manipulating the store directly.

The standard way to implement this is to use a design pattern called Redux, which is made available to React apps through the react-redux library.

I suggest you take a look at this tutorial to learn how you use the React Redux library in practice.

1.make the Display as Component and not PureComponent.

2.define a local state in Display

// default state..
state = {
 language: 'us',
}

3.console whether your'e getting language in Display's props(will mount).

//probably inside

this.props.location.state

4.then set the state

this.setState(prevState => ({
 ...prevState,
 language: --value--,
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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