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

Using Custom hooks in React the right way

我在理解 using/calling 我在函数内自定义挂钩的最佳方法时遇到了重大问题。在我最近的代码中,我试图在 app.js

中调用自定义获取挂钩

我想将以下属性(姓名和年龄)发送到我的服务器以处理那里的数据库存储,因此我打算在用户填写姓名和年龄后单击按钮时执行此操作。下面的代码

app.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

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 }
}

需要在组件呈现时调用挂钩,而不是在发生点击时调用。但是你可以让你的钩子 return 一个函数,然后在 handleClick 中调用那个函数。例如:

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" },
    });
  };
};