简体   繁体   English

如何将redux props分配给react js中的组件本地状态?

[英]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?因为我最近在 React.js 工作,我对如何将 redux props 分配给组件本地状态以用于编辑数据有疑问。我曾尝试将 redux props 分配给 state 并且它是 undefined can有人能帮我解决这个问题吗?

  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.您提供的代码似乎都没有使用 Redux。 If audit is coming back as undefined, I'd double check the props that you are passing into your stateful component.如果audit返回未定义,我会仔细检查您传递给有状态组件的道具。

Aside from making sure you are actually passing in redux props correctly.除了确保您实际上正确地传递了 redux 道具。 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.嗯,这是使用 redux、redux 操作/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).首先我们声明我们的 props(它们的类型,即使我们在 javascript 中它仍然是一个很好的实践),我们添加一个默认值,这里是错误变量(是 null 或来自你的 API 的错误对象或其他)。

Secondly, we add our props in the local state of the WrappedLogin Class.其次,我们在WrappedLogin类的本地状态中添加我们的道具。 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 .三、重要部分: static getDerivedStateFromProps(nextProps, prevState)有关更多信息, 请访问

basically, It should return an object to update the state, or null to update nothing.基本上, 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.想想lodash和很棒的方法pick和isEqual什么时候可以比较newProps和previousState,如果有更新那么方法返回新的props并且下一次渲染会有新的数据。

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.最后是将 redux 存储( 此处为 doc )(动作、状态等)与我们的组件连接的 redux 方法。

This aa good way i think to use reactjs, redux, props in a simple and effective way.我认为这是一种以简单有效的方式使用 reactjs、redux、props 的好方法。 Now it's up to you to adapt to what seems best, cheers :)现在由你来适应看起来最好的东西,干杯:)

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

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