如何从react-router的history.push中呈现具有传递状态的React Component

时间:2020-07-25 18:58:14

标签: reactjs react-router

我有一个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不适用于此用例?

0 个答案:

没有答案