如何使用useState()钩子和history.push()将状态传递给另一个组件

时间:2020-04-08 17:37:47

标签: reactjs react-router react-hooks

我正在尝试实现一个搜索栏,当用户开始键入内容时,会将用户移动到一个新视图,该视图显示该视图上的结果。

我有以下代码,该代码使用户可以开始搜索,将searchInput设置为一种状态,然后将用户移至新视图。

问题是:我无法从SearchBar组件传递和访问searchInput状态到SearchResultsView组件。

SearchBar.tsx

import * as React from 'react'
import { useState } from 'react';
import { useHistory } from 'react-router-dom';

export const SearchBar = () => {

    const [searchInput, setSearchInput] = useState('');
    const history = useHistory();

    const handleInputChange = (value: string) => {
        setSearchInput(value);
        history.push('/search-results', { searchInput: searchInput });
    }

    return (
        <input
            type="text" 
            value={searchInput}
            onChange={(e) => handleInputChange(e.target.value)}   
        />
    )
}

这里是SearchResultsView,我想在其中简单地访问searchInput查询(然后可以继续构建搜索逻辑)

import * as React from 'react'

export const SearchResultsView = (searchInput) => {

    // What I've tried that didn't work
    const query = searchInput // returns empty
    const state = useState('searchInput') // returns empty

    return (
        <div>
            {/* Searching for: {searchInput} */}
        </div>
    )
}

有关其他信息,这是我设置search-results路线的方法

export const App = () =>  {
  return (
    <HashRouter>
      <div>
        <AppSidebar/>
          <Switch>
            <Route path="/" exact render={() => <MainView/>}/>
            <Route path="/search-results" exact render={() => <SearchResultsView/>}/>
          </Switch>
        </div>
      </div>
    </HashRouter>
  )
}

1 个答案:

答案 0 :(得分:0)

使用history.push,您正在尝试将searchInput作为状态传递。可以在其他组件中作为location.state访问。但是请注意,searchInput在传递时未设置,因为设置状态是一个异步过程。

const handleInputChange = (value: string) => {
    setSearchInput(value);
    // searchInput is not yet set here, so using value
    history.push('/search-results', { searchInput: value });
}

如果要从状态中进行设置,可以为此使用useEffect

useEffect(() => {
  if(searchInput) {
    history.push('/search-results', { searchInput });
  }
}, [searchInput]);

在两种情况下,您都可以通过以下方式访问它:

const location = useLocation();

// location.state would be undefined if user is directly taking this url
const { searchInput } = location.state || { searchInput: '' };

如果希望用户使用参数链接到搜索页面,则可以使用查询参数。

Codesandbox Demo