如何将状态传递给路由器组件?

时间:2020-09-16 22:58:06

标签: reactjs react-router state

我对React还是很陌生,我正在尝试创建一个简单的游戏。 应用组件中的所有数据均处于状态。我想使用Router通过几个道具将页面重定向到 Battle 组件。我可以将状态从App传递到路由器,以便路由器可以将其传递给Battle组件,如下所示:

<Route path="/game/battle" component={
  <Battle
        monster = {this.props.details} //some props living
        team = {this.props.team}       //in App component
        player={this.props.player}     //can i pass it here somehow?
      }
  />

组件看起来像这样: Router => App(状态)=>战斗,以及onClick(更改路径)之后的某个地方,我 want Router => Battle(具有来自App状态的数据)=>战斗后返回App 。有办法实现吗? 感谢所有感兴趣的人

EDIT render prop解决了该问题,谢谢。 Router呈现通过道具传递的数据,但是将数据从其他组件状态传递到Router是一个好主意,如下所示:

<App  //this is where state with monster, team, player lives
 (...)
  <Router
        monster = {this.state.details} //some props living in this App component
        team = {this.state.team}       //can i pass it to Router somehow
        player={this.state.player}     //so Router renders Battle component 
                                       //with monster, team, player data?
      />
/>

编辑2 好的,因此我试图将Router组件放置在App组件内,并从App状态向其传递一些道具。在此App组件中,我也使用onClick将路径更改为/battle。在Router中,我使用渲染道具传递道具,但它使应用永久崩溃。我想我搞砸了...

Router.js: (...)

      <Route path="/game/:storeId" component={App} />

      <Route
       path="/battle"
       component={() => (
      <Battle
          player={this.props.player}
          team={this.props.team}
          monster={this.props.monster}
      />
      )}/>
      <Route component={NotFound} />
    </Switch>
  </BrowserRouter>
(...) export default Router;

App.js:

(...)
  state = {
    player: {},
    monsters: {},
    locations: {},
    team: {},
    battleMode:  false,
    communicate: "asdad",
    merchants: {},
    quests: {},
    items: {},
  };

(...) return(
                      <Router
        monster= {this.state.monster} //some props living in this App component
        team = {this.state.team}       //can i pass it to Router somehow
        player={this.state.player}     //so Router renders Battle component 
                                       //with monster, team, player data?
                />
          <button onClick={()=>{this.props.history.push(`/battle`)}}>Go →</button>

(...) 
)

解决方案:遵循此沙箱,这很棒: codesandbox.io/s/cranky-keller-hbig1?file=/src/App.js

1 个答案:

答案 0 :(得分:1)

您可以使用render prop

<Route
  path="/game/battle"
  render={() => (
    <Battle
      monster={this.props.details}
      team={this.props.team}
      player={this.props.player}
    />
  )}
/>

或者,您仍然可以使用component道具,但这会导致安装新组件

<Route
  path="/game/battle"
  component={() => (
    <Battle
      monster={this.props.details}
      team={this.props.team}
      player={this.props.player}
    />
  )}
/>
相关问题