【问题标题】:React - pass state to RouteReact - 将状态传递给 Route
【发布时间】:2020-07-23 21:00:43
【问题描述】:

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

组件A.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,但它始终未定义。有没有办法将这些参数传递给路由,还是我需要使用 Context 来解决这个问题?

【问题讨论】:

  • 您的会议和姓名可能有误。你放一个 , 而不是 ;

标签: reactjs react-router


【解决方案1】:

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

这是一个工作示例。它使用BrowserRouter,因为我无法让带有createBrowserHistory 的npm history 包在sn-p 中正确加载,但这与以这种方式创建历史并将其提供给您的常规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'))
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/5.0.1/react-router-dom.min.js"></script>
<div id="root"></div>

【讨论】:

    猜你喜欢
    • 2020-01-09
    • 2019-03-08
    • 2019-06-25
    • 2019-01-20
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2021-08-04
    相关资源
    最近更新 更多