gpt4 book ai didi

javascript - 如何使用 React Hooks 实现刷新按钮?

转载 作者:行者123 更新时间:2023-12-05 09:37:20 25 4
gpt4 key购买 nike

我正在尝试实现一个刷新按钮,但无法完成。

我的代码是这样的:

// ParentComponent.js
const ParentComponent = () => {
const { loading, error, data } = useItems();

return (
<ChildComponent items={data} />
);

... rest of my code that shows the data
};

// ChildComponent.js
const ChildComponent = ({ items }) => {
return (
// Logic that renders the items in <li>s
<button onClick={() => console.log('Clicking this button should refresh parent component')}
)
};

// services/useItems.js
const useItems = () => {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');

useEffect(() => {
axios
.get(API_URL + '/counter')
.then((response) => {
setItems(response.data);
setLoading(false);
})
.catch((error) => {
setLoading(false);
setError(error.message);
});
}, []);

return { loading, error, data: counters };

}

我尝试了几种方法,但都没有奏效。任何帮助将不胜感激:)

最佳答案

我不认为 useEffect 是这里的正确机制。由于这是命令式调用,因此没有任何反应,useState 可以很好地完成这项工作:

// ParentComponent.js
const ParentComponent = () => {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');

const refresh = () => {
axios.get(API_URL + '/counter').then((response) => {
setItems(response.data);
setLoading(false);
}).catch((error) => {
setLoading(false);
setError(error.message);
});
};
useEffect(refresh, []);

return (
<ChildComponent items={items} refresh={refresh} />
);

// ... rest of my code that shows the data
};

// ChildComponent.js
const ChildComponent = ({ items, refresh }) => {
return (
// Logic that renders the items in <li>s
<button onClick={refresh}>
Refresh
</button>
)
};

关于javascript - 如何使用 React Hooks 实现刷新按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64311350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com