简体   繁体   English

在 React 中正确使用自定义钩子

[英]Using Custom hooks in React the right way

I have been having major problems understanding the best approach to using/calling my custom hooks inside a function. in my resent code, I am trying to call a custom fetch hook in my app.js我在理解在 function 中使用/调用我的自定义挂钩的最佳方法时遇到了重大问题。在我重新发送的代码中,我试图在我的 app.js 中调用自定义获取挂钩

I want to send the following properties (name and age) to my server to handle database storage there, so i intend to have this action happen when the user clicks a button after filling in their name and age.我想将以下属性(姓名和年龄)发送到我的服务器以处理那里的数据库存储,所以我打算在用户填写姓名和年龄后单击按钮时发生此操作。 code below下面的代码

app.js应用程序.js

const [name, setName] = useState('Owen');
const [age, setAge] = useState(22);

const handleClick = () => {
//if statement to check that name and age where provided
  const {data,error} = useFetchPost('url',{name:name,age:age}); 
}

useFetchPost.js使用FetchPost.js

const useFetchPost = ({url, val}) => {
 
 const [data, setData] = useState(null);
 const [error, setError] = useState(null);

 useEffect(()=> {
  fetch(url,{method:'POST',header: {'Content-Type': 'application/json'}, 
  body:JSON.stringify(val)})
  .then(res =>  return res.json())
  .then(data => setData(data))
  .catch(err => setError(err))
 }, [url, val])

 return { data, error }
}

Hooks need to be called when the component renders, not when a click happens.钩子需要在组件渲染时调用,而不是在点击发生时调用。 But you can have your hook return a function, and then call that function in handleClick.但是您可以让钩子返回function,然后在 handleClick 中调用该 function。 For example:例如:

const useFetchPost = () => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  const doFetch = useCallback((url, val) => {
    fetch(url, {
      method: "POST",
      header: { "Content-Type": "application/json" },
      body: JSON.stringify(val),
    })
      .then((res) => res.json())
      .then((data) => setData(data))
      .catch((err) => setError(err));
  }, []);

  return { data, error, doFetch };
};

// used like:
const App = () => {
  const { data, error, doFetch } = useFetchPost();

  const handleClick = () => {
    doFetch(url, {
      method: "POST",
      header: { "Content-Type": "application/json" },
    });
  };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM