如何将状态对象值设置到 redux 存储中

How to set state object values into redux store

我有一个表单,其中有 2 个输入文本框。在它的更改处理程序上,我将它们各自的值设置到状态对象中。但是我想将这 2 个值存储到 redux 存储中,以便我可以在多个组件上使用它。无论如何我可以将这 2 个输入值存储到状态和 redux 存储中。下面是我的登录组件代码。提前致谢。

import React from "react";
import { connect } from "react-redux";
import * as loginAction from "../redux/actions/LoginAction";


class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",//want to have this value in redux store so that I can use it in multiple components
      password: "",
      errorUsername: null,
      errorPassword: null,
    };

    this.handleValidation = this.handleValidation.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
  //assign textbox values to props
  handleChange = (e) => {
    this.setState({
      [e.target.name]: [e.target.value],
    });
  };
  //handle input validation
  handleValidation = (event) => {
    if (!this.state.username) {
      this.setState({ errorUsername: "Please enter User Name" });
      event.preventDefault();
    }

    if (!this.state.password) {
      this.setState({ errorPassword: "Please enter Password" });
      event.preventDefault();
    }

    if (this.state.password && this.state.username) {
      this.setState({ errorUsername: null, errorPassword: null });
      let postData = {
        username: this.state.username[0],//want to have this value in redux store so that I can use it in multiple components
        password: this.state.password[0],
      };

      event.preventDefault();
      //dispatching an action
      this.props.dispatch(loginAction.checkLogin(postData, this.props.history));
    }
  };

  render() {
    return (
      <div className="d-flex flex-column">
        <div className="d-flex globalStyle">
          <div className="w-100 justify-content-start p-5">
            <div className="p-10 bg-white">
              <div className="Login">
                <form>
                  <div className="d-flex flex-column">
                    <div>Login</div>
                    <div className="d-flex flex-row">
                      <div>
                        <b>User name</b>
                      </div>
                    </div>

                    <div>
                      <input
                        type="username"
                        name="username"
                        className="inputText"
                        id="exampleInputUserName"
                        value={this.props.userName}
                        onChange={this.handleChange}
                        placeholder="Enter User Name"
                      ></input>
                    </div>

                    <div className="text-danger d-flex flex-row p-2 ml-2">
                      {this.state.errorUsername && (
                        <div>{this.state.errorUsername}</div>
                      )}
                    </div>

                    <div className="d-flex flex-row">
                      <div>
                        <b>Password</b>
                      </div>
                    </div>

                    <div className="d-flex flex-row p-2 ml-2">
                      <input
                        type="password"
                        name="password"
                        className="inputText"
                        value={this.props.password}
                        onChange={this.handleChange}
                        placeholder="Enter Password"
                      ></input>
                    </div>
                    <div className="text-danger d-flex flex-row p-2 ml-2">
                      {this.state.errorPassword && (
                        <div>{this.state.errorPassword}</div>
                      )}
                    </div>
                    <div className="d-flex flex-row  justify-content-around p-2 ml-2">
                      <button
                        type="submit"
                        onClick={this.handleValidation}
                        className="button-style"
                      >
                        Login
                      </button>
                    </div>
                  </div>
                  <div>
                    <br></br>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    userDetails: state.userDetails,
  };
}

export default connect(mapStateToProps)(Login);

Mu 登录操作代码是

const getUserDetailsSuccess = (userDetails) => ({
  type: "GET_DETAILS",
  userDetails,
});

export const checkLogin = (loginData, history) => {
  const url = `login`;
  return (dispatch) => {
    return service
      .post(url, loginData)
      .then((res) => {
        const userDetails = res.data.response_message;
        dispatch(getUserDetailsSuccess(userDetails));
      })
      .catch((error) => {
        throw error;
      });
  };
};

我的 Reducer 代码是

function loginReducer(state = { userDetails: {} }, action) {
  switch (action.type) {
    case "GET_DETAILS":
      return { userDetails: action.userDetails };
    default:
      return state;
  }
}

export default loginReducer;

我的代码工作正常,没有任何问题。

只需将 loginData 添加到您的发送中


const getUserDetailsSuccess = (userDetails, loginData) => ({
    type: "GET_DETAILS",
    userDetails,
    loginData
 });

export const checkLogin = (loginData, history) => {
 const url = `login`;
 return (dispatch) => {
   return service
     .post(url, loginData)
     .then((res) => {
       const userDetails = res.data.response_message;
       dispatch(getUserDetailsSuccess(userDetails, loginData));
     })
     .catch((error) => {
       throw error;
     });
  };
 };

在reducer中action.loginData会是你想要的内容(不知道你想怎么存储)


     function loginReducer(state = { userDetails: {} }, action) {
       switch (action.type) {
        case "GET_DETAILS":
           return { userDetails: { ...action.userDetails, ...action.loginData } };
        default:
          return state;
      }
     }

     export default loginReducer;