【发布时间】:2021-01-03 19:31:43
【问题描述】:
我对 React 很陌生,我正在尝试创建一个简单的游戏。 App 组件中的所有数据都处于状态。我想使用路由器将页面重定向到带有几个道具的 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(state) => Battle 和 onClick 之后的某个地方(更改路径)我 想要 Router => Battle(带有来自 App 状态的数据)=> 战斗后返回 App强>。有没有办法实现它? 感谢所有感兴趣的人
EDIT 渲染道具解决了这个问题,谢谢。 Router 渲染通过 props 传递的数据,但是像这样将数据从其他组件状态传递到 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
【问题讨论】:
标签: reactjs react-router state