阻止Redux重新渲染整个树并清除本地状态

时间:2020-10-28 12:20:31

标签: javascript reactjs redux

对于我的应用程序的注册表单,我正在使用本地组件状态维护表单值,但是currentUser状态,错误状态和API调用位于Redux中。

我想发生的事情是,当提交表单时,按钮有一个加载微调器,并且表单值一直保留到从服务器返回响应为止。如果服务器以授权用户响应,请重定向到app。如果有错误,则应清除表单的值。

问题似乎是Redux在调度任何状态更新功能时(无论是清除错误还是进行API调用以授权用户)都在清除我的表单值。有什么办法可以避免这种情况的发生?

从我的AuthForm.js

const submitData = () => {
    setLoading(true);
    if (formType === 'reset') {
      updatePassword(resetToken, values.password, history)
        .then(result => setLoading(false));
    } else if (formType === 'forgot') {
      forgotPassword(values.email, history);
    } else {
      console.log(values); // form values still populated
      onAuth(formType, values, history)
        .then(result => {
          console.log('result received'); // values empty
          setLoading(false);
            if (formType === 'signup') {
              history.push('/questionnaire')
            } else {
              history.push('/app')
            }
        })
        .catch(err => setLoading(false));
    }
  };

从我的redux actions.js文件中:

export function authUser(type, userData, history) {
  return dispatch => {
    dispatch(removeError());
    console.log('dispatch') // by this time the form values are empty
    // unless I comment out the dispatch(removeError()) above, 
    // in which case we still have values until 'token recevied' below
    return apiCall('post', `/users/${type}`, userData)
      .then(({ jwt, refresh_token, ...user }) => {
        console.log('token received')
        localStorage.setItem('jwtToken', jwt);
        localStorage.setItem('jwtTokenRefresh', refresh_token);
        dispatch(getUser(user.id));
      })
      .catch(err => {
        handleError(dispatch, err);
      });
  };
}

我还在AuthForm组件中记录了值。结果是这样的: enter image description here

编辑:肯定看起来我的组件正在卸下,但仍不清楚为什么我或如何防止它。 enter image description here

我试图记住分派功能,但似乎没有作用。

const dispatch = useDispatch();
  const onAuth = useCallback(
    (formType, values, history) => {
      dispatch(authUser(formType, values, history))
    },
    [dispatch]
  );

1 个答案:

答案 0 :(得分:0)

您的组件是redux商店的订阅者,这就是为什么它重新呈现, 组件的状态被初始化为初始状态, 现在,您需要一种在渲染周期内持久保留这些组件状态的方法。 在类组件上,您可以将值绑定到实例,即使用this.value == 'value' 以便在渲染之间保持相同,

要实现此功能,请使用名为useRef的钩子 除非您手动更改它,否则它不会在重新渲染时更改其值, 希望会有所帮助

相关问题