发送状态与反应路由器不工作

Lef*_*eff 5 reactjs react-router

我正在我的项目中使用react version ^16.8.1and 。 我正在尝试使用 React 路由器发送状态片段,如下所示:react-router-dom version ^4.3.1

      this.props.history.push({
        pathname: '/',
        state: {
          successMessage: this.generateSuccessMessage(payload)
        }
      });
Run Code Online (Sandbox Code Playgroud)

在另一个组件中,我试图获取该状态并将其作为道具发送给子组件,如下所示:

successMessage={this.props.location.state ? this.props.location.state.successMessage : null}
Run Code Online (Sandbox Code Playgroud)

null但是,每次触发推送时我都会收到。我已经检查了state反应开发工具中的 ,并使用 Jest 进行了测试,但两者都表明state没有被转发到其他组件。以下是相关路线。我正在将状态推向OppgaveEditor历史,并尝试将其放入Dashboard组件中。

     <Switch>
          <Route exact path="/" render={(props) => <Redirect to="/dashboard" />} />
          <Route path="/dashboard" render={(props) => <Dashboard user={this.state.user} {...props} ><OppgaveDashboard/></Dashboard>}/>} />
          <Route path="/oppgave-editor/:id" render={(props) => <OppgaveEditor user={this.state.user} {...props} />}/>
          <Route component={NotFound}/>
     </Switch>
Run Code Online (Sandbox Code Playgroud)

我做错了什么,我该如何解决这个问题?

Gaë*_*l S 6

state我猜你在重定向到“/”期间丢失了。你需要转发它。

它应该给你这样的东西:

 <Route exact path="/" render={(props) => <Redirect to={{
      pathname: '/',
      state: this.props.location.state
    }}
 />
Run Code Online (Sandbox Code Playgroud)