首页 > 解决方案 > 使用 Hooks 时在 onPress 之前调用反应按钮

问题描述

我正在尝试请求API request使用钩子。但我的问题是我的函数在 I 之前被调用onPress

我有一个这样的自定义 API 组件:

const FetchDataPut = (URL) => {

  useEffect(() => {
      async function fetchData() {
          const res = await axios({
                    method: 'put',
                    url: URL,
                    data:{
                      name:'111',
                      email:'222',
                      password:'333',
                      id:'444',
                      phone:'555'
                    }
                  });
          const response = await res;
          console.log(response, 'completed')
      }
      fetchData()
  },[])
  return null
}

我可以从console.log那个 api 请求中看到completed。我的问题是api component在我按下按钮之前调用了我的。

这是我的按钮组件:

const EditAccount = (props) => {

  const Desktop = () => {
    const URL = `MyURL...`
    return (
      <View>
        <Button title='edit account' onPress={FetchDataPut(URL)}/>
      </View>
    )
  }

  return(
    <div>
      <Desktop/>
    </div>
  )
}

如果我将我onPress的函数更改为这样的箭头函数: onPress={()=>FetchDataPut(URL)}在我之前不会调用组件onPress。但它会给我一个错误Invalid hook call. Hooks can only be called inside of the body of a function component

任何想法如何我的 api 请求当onPressButton

任何意见或建议都会非常有帮助。提前致谢!:)

标签: reactjsreact-nativereact-hooks

解决方案


我认为要走的路是使用钩子而不是组件:

const useFetchDataPut = () => {
    const [url, setUrl] = useState("");

    useEffect(() => {
        if (!url) return;

        async function fetchData() {
            const res = await axios({
                method: "put",
                url,
                data: {
                    name: "111",
                    email: "222",
                    password: "333",
                    id: "444",
                    phone: "555"
                }
            });
            const response = await res;
            console.log(response, "completed");
        }
        fetchData();
    }, [url]);

    return setUrl;
};

然后在按下按钮时调用它。也Desktop应该在EditAccount组件之外定义。

const Desktop = () => {
    const setUrl = useFetchDataPut();

    return (
        <View>
            <Button
                title="edit account"
                onPress={() => setUrl("https://...")}
            />
        </View>
    );
};

const EditAccount = props => {
    return (
        <div>
            <Desktop />
        </div>
    );
};

如果有不清楚的地方,请告诉我。


推荐阅读