我有一个Component来显示这样的书列表,该书可以使用useReducer处理状态:
const Books: React.FC = () => {
const location = useLocation<BooksListState>();
const booklist: BooksListState = { ...booksListDefaultState, ...location.state };
const [state, dispatch] = useReducer(reducer, booklist);
return (<BookList state={state} dispatch={dispatch} />);
};
BooksListState
是具有以下属性的接口:
export interface BooksListState {
searchBoxText: string;
searchResultsPageEnabled: boolean;
books: Book[];
}
booksListDefaultState
是符合BooksListState
接口的对象:
const booksListDefaultState: BooksListState = {
searchBoxText: '',
searchResultsPageEnabled: false,
books: [],
}
BookList
是显示书籍并具有用于过滤书籍的搜索框的组件。
我的意图是从其他任何页面导航到Books
设置为searchResultsPageEnabled
的{{1}}组件,为此,我正在使用以下代码:
true
我正在将const history = useHistory();
const booklistState: BooksListState = {
searchBoxText: '',
searchResultsPageEnabled: true,
books: [],
};
const handleClick = () => {
history.push('/landing/books', booklistState);
};
传递给不同页面中的许多按钮。该处理程序正在工作,正在正确地导航到Books组件,并且我可以看到传递的状态也是正确的,问题是,在将handleClick
状态传递给reducer之后,我收到了{{ booklist
中的1}}。例如:
false
查看状态变化的唯一方法是刷新页面。
我以为searchResultsEnabled
仅将我重定向到const location = useLocation<BooksListState>(); //location.state is coming as expected (searchResultsPageEnabled is true)
const booklist: BooksListState = { ...booksListDefaultState, ...location.state }; // after destructuring, booklist is: { searchBoxText: '', searchResultsPageEnabled: true, books: [] }
const [state, dispatch] = useReducer(reducer, booklist); // here's the problem
console.log(`searchResultsPageEnabled: ${state.searchResultsPageEnabled}); // this is returning FALSE, even though the state variable passed above (booklist.searchResultsPageEnabled) is true
return (<BookList state={state} dispatch={dispatch} />);
组件,但没有通过传递的道具重新渲染,或者history.push
在以下情况下不返回新状态使用Books
。我需要改变什么吗?还是reducer
不适用于此用例?