Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 自定义钩子-基于API调用的设置值_Reactjs_React Hooks - Fatal编程技术网

Reactjs 自定义钩子-基于API调用的设置值

Reactjs 自定义钩子-基于API调用的设置值,reactjs,react-hooks,Reactjs,React Hooks,概述 我编写了一个钩子,它通过一个函数执行XHR请求,并根据该XHR请求的返回值设置状态。我想分享执行XHR请求的函数以及状态值和setter 代码 export function useOpenItems() { const [count, setCount] = useState(0); useEffect(() => { get_open_items(); }, [count]); function get_open_items() { const

概述

我编写了一个钩子,它通过一个函数执行XHR请求,并根据该XHR请求的返回值设置状态。我想分享执行XHR请求的函数以及状态值和setter

代码

export function useOpenItems() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    get_open_items();
  }, [count]);

  function get_open_items() {
    const response = get_data('/my/api/endpoint`);
    response.then(
      function(res) {
        setCount(res.data.length);
      }.bind(this)
    );
  }

  return [count, setCount, get_open_items];
}
仅供参考-如果您好奇,我的“get_data”函数只是一个AXIOS包装器,如:

export async function get_data(endpoint) {
    return await axios.get(endpoint);     
}
这是使用钩子的正确方法吗?我希望能够调用get_open_items()函数来更新最终由几个不同组件呈现的计数

编辑:添加引用更新计数的组件:

export function ListItems() {
  const [count, setCount] = useOpenItems();

  return (
    <List>

      <ListItem button component={Link} to="/requests">
        <ListItemIcon>
          <Badge badgeContent={count} color="secondary">
            <Requests />
          </Badge>
        </ListItemIcon>
        <ListItemText primary="Requests" />
      </ListItem>

    </List>
  );
}
导出函数列表项(){
const[count,setCount]=useOpenItems();
返回(
);
}

好的,这似乎是合法的。唯一可能需要清理的东西

xport function useOpenItems() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    get_open_items();
  }, [count]);

  async function get_open_items() {
    const response = await get_data('/my/api/endpoint`); // You are already using async/await in get_data, so you can there
    setCount(response.data.length);
  }

  return [count, setCount, get_open_items];
}

我已经用使用钩子的组件更新了我的原始帖子。看起来我可能需要一个useEffect函数来更新计数?感谢您的反馈