在反应本机useEffect()中获取无效的钩子调用

时间:2020-07-03 10:04:04

标签: javascript reactjs react-native react-hooks

我想从axios发布数据,但是出现无效的挂接调用错误。我在这里做错了。 这是我的代码

all

1 个答案:

答案 0 :(得分:2)

您必须在顶层调用挂钩,请参见Rules Of Hooks

不要在循环,条件,或嵌套函数中调用挂钩。

const Login = (props) => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetch = async () => {
      const url = baseUrl + "/";
      const loginData = {
        email: email,
        password: password,
      };

      await axios
        .post(`${url}users/login`, loginData)
        .then((res) => {
          console.log(res.data);

          AsyncStorage.setItem("token", JSON.stringify(res.data.token));

          props.navigation.navigate("MainHome");
        })
        .catch((error) => {
          setError(error.res.data);
          setLoading(false);
          setIsLoading(false);
        });
    };
    if (loading) {
      fetch();
    }
  }, [loading, email, password]);

  const onLoginSubmit = (event) => {
    event.preventDefault();
    setIsLoading(true);
  };
};