简体   繁体   中英

how to assign redux props to a component local state in react js?

As i am recently working in React.js and i am having a doubt on how to assign a redux props to component local state for the use of editing the data .I had tried of doing assigning starightly redux props to state and it is undefined can anyone just help me how to fix this is issue?

  constructor(props) {
  super(props);
  this.state = {
  editMode: false,
  originalAudit: this.props.Furlenco.furlencoAudits,
  **editedAudit: this.props.Furlenco.furlencoAudits**,
  selectedAudit: null,

};
  changeAnswer = (question, answerObject) => {
  let answer = "";
  let audit = this.state.editedAudit;
  console.log(audit)

}

here the audit is undefined.how to fix this issuse

None of the code you provided appears to use Redux. If audit is coming back as undefined, I'd double check the props that you are passing into your stateful component.

Aside from making sure you are actually passing in redux props correctly. I would try adding this line into the constructor:

  this.changeAnswer = this.changeAnswer.bind(this)

      constructor(props) {
        super(props);
        this.state = {
          editMode: false,
          originalAudit: this.props.Furlenco.furlencoAudits,
          **editedAudit: this.props.Furlenco.furlencoAudits**,
          selectedAudit: null,
        };
        console.log(this.props); // make sure its populated with data

        this.changeAnswer = this.changeAnswer.bind(this)
}

Well I think the code speaks for itself

import React from 'react';
import _ from 'lodash';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as AuthActions from '../../core/redux/Auth/actions.js';
import * as AuthSelector from '../../core/redux/Auth/selector.js';

class WrappedLogin extends React.Component {
    static propTypes = {
        isPending: PropTypes.bool.isRequired,
        postAuth: PropTypes.func.isRequired,
        error: PropTypes.object,
        isAuth: PropTypes.bool.isRequired,
    };

    static defaultProps = {
        error: null,
    };

    constructor(props) {
        super(props);
        this.state = {
            error: props.error,
            isPending: props.isPending,
            isAuth: props.isAuth,
        };
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit() {
        const { postAuth } = this.props;

        postAuth(userName, password);
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        const keys = [
            'isPending',
            'error',
            'isAuth',
        ];

        const mutableProps = _.pick(nextProps, keys);
        const stateToCompare = _.pick(prevState, keys);

        if (!_.isEqual(mutableProps, stateToCompare)) {
            return mutableProps;
        }

        return null;
    }

    render () {
        const { isPending } = this.state;

        return (
            <Spin spinning={ isPending } delay={ 500 }>
                <LayoutLogin>
                    <CustomForm ...this.state>
                </LayoutLogin>
            </Spin>
        );
    }
}

function mapStateToProps(state) {
    return {
        isPending: AuthSelector.getIsPending(state),
        error: AuthSelector.getError(state),
        isAuth: AuthSelector.getIsAuth(state),
    };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ ...AuthActions }, dispatch);
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(WrappedLogin));

Well this is a simple extract of a Login Page using redux, redux actions / reducers. First we declare our props (their type, even we are in javascript it still a good pratice) and we add a default value , here for the error variable (is null or the error object from your API or whatever).

Secondly, we add our props in the local state of the WrappedLogin Class. Never forget to bind all methods of our class.(the rule is simple, if the method change the local state of your component you have to bind it).

Third, the BIG PART : static getDerivedStateFromProps(nextProps, prevState) For more info about go to .

basically, It should return an object to update the state, or null to update nothing. just before the render method. We define the variable we want to be updated. Think to lodash and the greatful method pick and isEqual when can compare the newProps with the previousState, if there is an update so the method return the new props and the next rendering will have the new data.

After it's just a simple render where you can do whatever you want with your variable. Here it's just an example. And finally the redux method to connect the redux store( here doc ) (action, state,...) with our component.

This aa good way i think to use reactjs, redux, props in a simple and effective way. Now it's up to you to adapt to what seems best, cheers :)

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