【问题标题】:React Redux action payload data undefinedReact Redux 操作负载数据未定义
【发布时间】:2019-04-12 17:01:13
【问题描述】:

我正在尝试为我的应用设置身份验证。数据由 axios 返回并正确调用动作有效负载。当我尝试访问有效负载中包含的数据时,问题就出现了。它返回未定义。

使用 redux-form 登录组件:

class Signin extends Component {
  submit = values => {
    this.props.signInAction(values, this.props.history);
  };

  errorMessage() {
    if (this.props.errorMessage) {
      return <div className="info-red">{this.props.errorMessage}</div>;
    }
  }

  render() {
    const { handleSubmit } = this.props;
    return (
      <form onSubmit={handleSubmit(this.submit)} className="formu">
        <div>
          <div className="inputf">
            <Field
              name="login"
              component="input"
              type="text"
              placeholder="Username"
            />
          </div>
        </div>
        <div>
          <div className="inputf">
            <Field
              name="password"
              component="input"
              type="password"
              placeholder="Password"
            />
          </div>
        </div>
        <div>
          <button className="bsignin" type="submit">
            Sign in
          </button>
          {this.errorMessage()}
        </div>
      </form>
    );
  }
}

function mapStateToProps(state) {
  return { errorMessage: state.auth.error };
}

const reduxFormSignin = reduxForm({
  form: "signin"
})(Signin);

export default connect(
  mapStateToProps,
  { signInAction }
)(reduxFormSignin);

动作创建者

export function signInAction({ login, password }, history) {
  return async dispatch => {
    try {
      const res = await HTTP.post(`authenticate`, {
        login,
        password
      });
      localStorage.setItem("token", res.data.token);
      const req = await HTTP.get("account");
      dispatch({
        type: AUTHENTICATED,
        payload: req.data
      });
      history.push("/");
    } catch (error) {
      dispatch({
        type: AUTHENTICATION_ERROR,
        payload: "Invalid userName or password"
      });
    }
  };
}

减速器

import {
  AUTHENTICATED,
  UNAUTHENTICATED,
  AUTHENTICATION_ERROR
} from "../actions";

const initialState = {
  login: "",
  authority: ""
};

export default function(state = initialState, action) {
  switch (action.type) {
    case AUTHENTICATED:
      //This console log works and returns the data
      console.log(action.payload);
      //Next console log returns payload is undefined
      //console.log(action.payload.login);
      return {
        ...state,
        authenticated: true,
        // login: action.payload.login,
        // authority: action.payload.authority
      };
    case UNAUTHENTICATED:
      return { ...state, authenticated: false };
    case AUTHENTICATION_ERROR:
      return { ...state, error: action.payload };
    default:
      return state;
  }
}

我想使用来自有效负载的数据设置登录和权限,但无法访问其中的数据。 ¿ 我错过了什么?

【问题讨论】:

    标签: reactjs react-redux redux-thunk


    【解决方案1】:

    Redux Form 有一个 onSubmit 函数,它直接接受一个动作 https://redux-form.com/8.1.0/examples/remotesubmit/

    <form onSubmit={handleSubmit} className="formu">
    

    然后包装在 Redux Form 中

      const reduxFormSignin = reduxForm({
      form: "signin",
      onSubmit: signInAction
    })(Signin);
    
    

    在 Redux Debugger 中检查,你应该看到 redux 表单记录数据 还记得将表单减速器传递到您的商店,如此处所述https://redux-form.com/8.1.0/docs/gettingstarted.md/

    import { createStore, combineReducers } from 'redux'
    import { reducer as formReducer } from 'redux-form'
    
    const rootReducer = combineReducers({
      // ...your other reducers here
      // you have to pass formReducer under 'form' key,
      // for custom keys look up the docs for 'getFormState'
      form: formReducer`enter code here`
    })
    
    

    【讨论】:

    • 我遇到的问题与表单中的数据无关,而是来自 /account 的 axios 请求的数据。我收到令牌并从帐户中获取数据,但我无法将其分配给减速器上的状态。
    • ok 试试类似let payload = action.payload; let data = { data: payload, errors: {} }; return { ...state, ...data, authenticated: true } 这样的数据可以在状态内可用,您可以通过道具检索这些数据以执行任何操作
    • 好吧,有点工作。现在的问题是,当我更改路由时,“已验证”属性仍然存在,但数据不存在。 ¿ 如何使数据持久化?感谢您的回答,它们对于反应初学者非常有用。
    • 听起来 mapStateToProps 可以帮助您实现,或者如果您需要数据,您可以再次调用 AUTHENTICATED 方法,这样您就可以将 data 传递到新路线上的 initialState
    • 我在没有数据的情况下从路由器调用 AUTHENTICATED 方法。非常感谢,你帮了大忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2019-05-17
    • 2018-10-14
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多