在React中的路由器组件之间传递数据

时间:2020-07-07 01:41:34

标签: reactjs react-router react-router-dom

我有一个基于react-router-dom的应用程序,其中当前有两个屏幕:一个屏幕用于初始设置,第二个屏幕需要从第一个屏幕获取一些信息。该信息存储在主页代码中的常量中,我想知道是否存在一种在它们之间共享变量的方法,或者以某种方式将它们传递给第二个变量。下面的代码和树提供了基本的设置方法。

结构:

                         App
                          |
                        Routes
                          |
                    BrowserRouter
      ____________________|____________________
     |                                         |
   Route                                     Route
    Home ———— history.push("/in-game") ———> InGame
                      (+data)

家庭代码段:

const history = useHistory();
const toGame = () => history.push('/in-game');

const [colors, setColors] = useState();——————————
const [map, setMap] = useState();————————————————|—————————data I'd like to share with the InGame component
const [myColor, setMyColor] = useState();————————

真的希望我能对此有所帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以为此使用历史记录对象。

将路线从“家”更改为“ ingame”,并将其他数据传递到“ ingame”,

Home.js

const someEventHandler = event => {
       history.push({
           pathname: '/in-game',
           state: { map: map }
       });
    };

要在“ InGame”中访问它,

InGame.js

 const location = useLocation();

 console.log(location.state.map); //map value is available here

尝试以上。有关历史的更多信息,https://reactrouter.com/web/api/history请参阅react-router中的这些文档。

答案 1 :(得分:0)

此帮助

<Router>
  <Switch>
    <Route
        path="/in-game/:data/:data2"
        render={(props) => <InGame {...props} />}
    />
  </Switch>
</Router>

这意味着您可以在游戏URL中传递两个参数作为get参数。这两个参数可以在InGame组件中解析为this.props.match.params

要在任何地方调用此URL,可以使用(示例)

<a href="/in-game/param1/param2">Click me</a>

history.push("/in-game/param1/param2")

请参阅此帖子:How to access 'this.props.match.params' along with other props?