使用 useContext 和 useReducer 进行状态管理,使用 useEffect 获取数据
State management with useContext and useReducer and fetching data with useEffect
我有一个 React 应用程序,它使用 useContext 和 useReducer 管理其全局状态。我的 BookList
组件需要在安装时从服务器获取书籍。如果获取书籍成功,它们应该存储在全局状态中。
我的方法如下
function BookList() {
const [state, dispatch] = useContext(BookContext);
const [loading, setLoading] = useState(true);
useEffect(() => {
BookService
.fetchBooks()
.then(resp => {
setLoading(false);
dispatch({
type: FETCH_BOOKS,
books: resp.data
});
});
}, []);
return (
<div>
{loading
? "Loading ..."
: state.books.map(book => (
<div key={book.id}>{`${book.title} - $${book.price}`}</div>))
}
</div>
);
}
这有效但会产生警告
React Hook useEffect has a missing dependency: 'dispatch'. Either ...
我是否必须将 dispatch
添加到依赖项数组才能消除警告,或者有更好的方法吗?
警告在这里不是很相关,因为文档建议从 useEffect
的依赖项列表中省略 dispatch
,但您可以安全地将它放在依赖项数组中,因为它的身份始终稳定.
doc 说:
React guarantees that dispatch
function identity is stable and won’t change on re-renders.
This is why it’s safe to omit from the useEffect or useCallback dependency list.
我有一个 React 应用程序,它使用 useContext 和 useReducer 管理其全局状态。我的 BookList
组件需要在安装时从服务器获取书籍。如果获取书籍成功,它们应该存储在全局状态中。
我的方法如下
function BookList() {
const [state, dispatch] = useContext(BookContext);
const [loading, setLoading] = useState(true);
useEffect(() => {
BookService
.fetchBooks()
.then(resp => {
setLoading(false);
dispatch({
type: FETCH_BOOKS,
books: resp.data
});
});
}, []);
return (
<div>
{loading
? "Loading ..."
: state.books.map(book => (
<div key={book.id}>{`${book.title} - $${book.price}`}</div>))
}
</div>
);
}
这有效但会产生警告
React Hook useEffect has a missing dependency: 'dispatch'. Either ...
我是否必须将 dispatch
添加到依赖项数组才能消除警告,或者有更好的方法吗?
警告在这里不是很相关,因为文档建议从 useEffect
的依赖项列表中省略 dispatch
,但您可以安全地将它放在依赖项数组中,因为它的身份始终稳定.
doc 说:
React guarantees that
dispatch
function identity is stable and won’t change on re-renders.
This is why it’s safe to omit from the useEffect or useCallback dependency list.