React组件没有从Reducer获取更新状态

时间:2020-10-10 07:49:55

标签: javascript reactjs redux react-hooks react-component

我是新来的反应者,第一次尝试使用redux钩子,并在这一问题上停留了一天。终于想到了加入论坛。我在这里附上代码的屏幕截图。

当我提交表单时,成功方案运行良好。它正在将请求发送到用户正确保存到数据库的后端!问题出在错误情况下,用户提交带有已接收电子邮件的表单。在这种情况下,不会调用(auth.error)的if块,因为状态没有从reducer获取错误对象。

const Signup = () => {
  debug('In the Render shit!');
  const auth = useSelector((state) => state, shallowEqual);
  const dispatch = useDispatch();
  const [values, setValues] = useState({
    name: 'Rahul',
    lastname: 'Kodu',
    email: 'rahul.kodu@entr.co',
    password: '12345',
    success: false,
  });

  const { name, email, password, success, lastname } = values;

  const handleChange = (event) => {
    setValues({
      ...values,
      [event.target.name]: event.target.value,
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    //make thunk call here
    debug('Submit Button Clicked');
    const user = { name, email, password, lastname };
    dispatch(signUpUser(user))
      .then(() => {
        debug('In then of thunk!');
        //Finale
        debug(auth);
        if (auth.error) {
          setValues({ ...values, success: false });
          toast.error('Email Already Taken');
        } else {
          toast.info('? Signed Up! Now Sign in!');
          setValues({
            email: '',
            password: '',
            name: '',
            lastname: '',
            success: true,
          });
        }
        //finale
      })
      .catch((err) => {
        debug('In err of thunk' + err);
      });
  };
  const successMessage = () => {
    if (success) {
      return <Redirect to="/signin"></Redirect>;
    }
  };

  const signUpForm = () => {
    return (
      <div className="row">
        <div className="col-md-6 offset-sm-3 text-left">
          <form onSubmit={handleSubmit}>
            <div className="form-group">
              <label htmlFor="name-field">Name</label>
              <input
                className="form-control"
                type="text"
                id="name-field"
                name="name"
                value={name}
                onChange={handleChange}
                required
              />
            </div>
            <div className="form-group">
              <label htmlFor="name-field">Last name</label>
              <input
                className="form-control"
                type="text"
                id="lastname-field"
                name="lastname"
                value={lastname}
                onChange={handleChange}
                required
              />
            </div>
            <div className="form-group">
              <label htmlFor="email-field">Email</label>
              <input
                className="form-control"
                type="email"
                id="email-field"
                name="email"
                value={email}
                onChange={handleChange}
                required
              />
            </div>
            <div className="form-group">
              <label htmlFor="password-field">Password</label>
              <input
                className="form-control"
                type="password"
                id="password-field"
                name="password"
                value={password}
                onChange={handleChange}
                required
              />
            </div>
            <div className="form-group">
              <button
                type="submit"
                className="btn btn-sm btn-custom btn-block mt-5"
              >
                Sign-up!
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  };

  return (
    <Base title="Signup Page" description="Exisitng user? Goto Signin">
      {JSON.stringify(auth)}
      {signUpForm()}
      {successMessage()}
    </Base>
  );
};

动作的异步部分。重击部分如下。 Promise的错误部分在于提出问题。

//thunk
export const signUpUser = (user) => {
  return function (dispatch) {
    dispatch(beginApiCall());

    const options = {
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    };

    return axios
      .post(config.API + 'signup', user, options)
      .then((response) => {
        debug('In success of axios');
        dispatch(signUpUserSuccess(response.data));
      })
      .catch((err) => {
        debug('In err of axios');
        dispatch(signUpUserFailure(err.response.data));
        dispatch(apiCallError());
      });
  };
};

在化简器中,我将使用传播语法根据不变性规则返回用于故障情况的新对象(SIGNUP_USER_FAILURE)。

const authReducer = (state = initialState.auth, action) => {
  switch (action.type) {
    case types.LOAD_PROFILE:
      if (!action.newAuth) {
        action.newAuth = state;
      }
      return action.newAuth;

    case types.SIGNUP_USER_SUCCESS:
      if (!action.user) {
        action.user = state;
      }
      debug(action.user);
      return { ...action.user };
    case types.SIGNUP_USER_FAILURE:
      return { ...state, ...action.error };
    default:
      return state;
  }
};

但是,状态在reducer中已更新,但是组件未获取已更新状态以采取措施。但是在下一次渲染之后,组件正在获取数据。我认为渲染存在问题。请在这里帮助我。我

0 个答案:

没有答案