反应-将状态传递给路由

时间:2020-07-23 21:00:43

标签: reactjs react-router

我有一个简单的React + Hooks webapp,我有一个呈现componentA的route1。 在ComponentA上,如果满足条件,我可以为该组件呈现适当的jsx或重定向到Route2。 在route2上,我需要从route1呈现的componentA中获取一些状态。

ComponentA.jsx

return (
        <Fragment>
            {!call ? 
                (
                    <div className="container">
                        //some jsx
                    </div>
                )
                : 
                (
                    <Redirect to={{pathname: '/route2', state: { meeting, name }}}/>
                )}
        </Fragment>
);

App.js

const App = () => {

    return(
        <AuthProvider>
            <Router history={history}>
                <Switch>
                    <Route exact path="/route1" component={ComponentA} />
                    <Route exact path="/route2" component={ComponentB} />
                </Switch>
            </Router>
        </AuthProvider>
    );
};

我试图在ComponentB.jsx上获取状态props.location.state,但是它始终是未定义的。有没有办法将这些参数传递给路由,还是需要使用上下文来解决?

1 个答案:

答案 0 :(得分:0)

您的代码应该可以使用,但是props.location.state将是未定义的,除非您通过程序导航专门设置。例如,如果您重新加载页面,或者通过URL导航,或者在未设置页面的情况下导航,则该页面将不存在。您必须在组件中考虑到这一点,并且应该避免在其中放置任何需要可用的数据,无论到达路线的方式如何。通常,最好将所有共享状态存储在共享父目录中,在这种情况下为App

这是一个可行的例子。它使用BrowserRouter,因为我无法使用history来获得npm createBrowserHistory软件包,以正确地将其加载到代码段中,但实际上与以这种方式创建历史并将其馈送到常规{{ 1}}:

Router
const { useState } = React;
const { BrowserRouter, Switch, Route, Redirect } = window.ReactRouterDOM;

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/route1" component={ComponentA} />
        <Route exact path="/route2" component={ComponentB} />
        <Redirect to="/route1" />
      </Switch>
    </BrowserRouter>
  );
};

function ComponentA() {
  const [redirect, set] = useState(false);
  const string = "state preserved";

  return redirect ? (
    <Redirect to={{ pathname: "/route2", state: { string } }} />
  ) : (
    <button onClick={() => set(true)}>Redirect with state</button>
  );
}

function ComponentB(props) {
  return (
    <div>{props.location.state ? props.location.state.string : "no state"}</div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'))