状态未在指定函数内更新

时间:2020-11-12 11:20:43

标签: react-native

所以我正试图改变我的状态

export default function RegisterScreen({navigation}) {
  const {register, control, handleSubmit, errors} = useForm({
    resolver: yupResolver(schema),
  });
  const [state, setState] = useState({current_state: 'initial'});

  const onSubmit = (data) => {
    console.log(state.current_state);
    setState({current_state: 'login_process'});
    console.log(state.current_state);
  });
}

内部提交。但状态没有改变,它停留在initial

然后我正在尝试这样做

   console.log(this.state.current_state);
    this.setState({current_state: 'login_process'}, () => {
      console.log(this.state.current_state);
    });

但是我得到这个错误

可能的未处理的承诺拒绝(标识:0):TypeError:未定义是 不是对象(评估“ _this.state.current_state”)

我该如何解决?这是在本机反应中进行状态管理的正确方法吗?

2 个答案:

答案 0 :(得分:0)

我认为问题不在代码中,而不是放在 e.preventDefault()

尝试以下操作:

     const onSubmit = (e,data) => {
        e.preventDefault()
      console.log(state.current_state);
      setState({current_state: 'login_process'});
      console.log(state.current_state);
    });
  }

答案 1 :(得分:0)

您不能使用useState挂钩执行异步操作。如果要触发更改,请尝试以下操作:

export default function RegisterScreen({navigation}) {
  const {register, control, handleSubmit, errors} = useForm({
    resolver: yupResolver(schema),
  });
  const [state, setState] = useState({current_state: 'initial'});

  useEffect(() => {
    console.log(`state.current_state has been changed to: ${state.current_state}`)
  }, [state.current_state])

  const onSubmit = (data) => {
    console.log(state.current_state);
    setState({current_state: 'login_process'});
    console.log(state.current_state);
  });
}

您收到的错误是您不能在功能组件中使用this

您可以使用useEffect钩进一步操作,并执行以下操作:

useEffect(() => {
  if(state.current_state === 'login_process') {
    // add some logic that should happen when login is processing
  }
}, [state.current_state])