Reactjs React路由器不会将阵列作为组件的道具
我试图将一组对象作为道具传递到新路线。但是,每当我在浏览器上传递道具并转到该路径时,我都可以看到(使用console.log)道具中的数组存在,但它是空的。我不知道如何解决这个问题。我已经验证了数组在作为道具传递之前已填充Reactjs React路由器不会将阵列作为组件的道具,reactjs,react-router,react-router-v4,Reactjs,React Router,React Router V4,我试图将一组对象作为道具传递到新路线。但是,每当我在浏览器上传递道具并转到该路径时,我都可以看到(使用console.log)道具中的数组存在,但它是空的。我不知道如何解决这个问题。我已经验证了数组在作为道具传递之前已填充 class App extends React.Component { constructor(props) { super(props); this.state = { routes: [] }
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
routes: []
}
}
addToRoute(record){
let tempRoutes = this.state.routes.slice();
tempRoutes[record.id] = record;
this.setState({
routes: tempRoutes
})
}
render() {
return (
<div>
<Route exact path='/' render={() => <Subapp addToRoute={(record) => this.addToRoute(record)}/>}/>
<Route path={"/record/:id"} render={({match})=><BasicInfo match={match} {...this.state}/>}/>
</div>
);
}
}
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
路线:[]
}
}
地址路由(记录){
设tempRoutes=this.state.routes.slice();
tempRoutes[record.id]=记录;
这是我的国家({
路线:临时路线
})
}
render(){
返回(
this.addToRoute(记录)}/>
}/>
);
}
}
我不确定你的应用程序哪里出了问题,但我确实看到你的代码中有几个明显的部分在我试图重新创建你的问题时绊倒了我的应用程序
<Route exact path='/' render={() => <Subapp addToRoute={(record) => this.addToRoute(record)}/>}/>
在可能的情况下,限制自己传递整个状态。相反,试着明确定义你需要的道具。如果不这样做,将来可能会扩展组件中的状态。然后,这些州的新部分也被传递了。此外,显式定义道具将使代码更具可读性
this.state = {
routes: []
}
addToRoute(record){
let tempRoutes = this.state.routes.slice();
tempRoutes[record.id] = record;
this.setState({
routes: tempRoutes
})
}
这行不通state
最初是一个数组,而在addToRoute()
中将其转换为一个对象
因此,代码中确实存在一些不一致之处。在试图重新创建您的问题时,由于这些错误,我无法使代码正常工作。经过一些调整后,它运行。正如您所看到的,我正在传递routes对象,它填充在
中。请看一个工作示例
如果这回答了您的问题,请告诉我。使用redux state您能说出第二条路由中的匹配吗?@ShubhamAgarwalBhewanewala这是基本的react路由器内容显示错误值的控制台日志在哪里?显示BasicInfo组件?谢谢您的回答,但它似乎并没有解决问题。似乎React路由器正在接收我的初始路由,但在调用addToRoute时它从不更新。使其始终为空数组(或对象,具体取决于实现)。有没有办法解决这个问题?
this.state = {
routes: []
}
addToRoute(record){
let tempRoutes = this.state.routes.slice();
tempRoutes[record.id] = record;
this.setState({
routes: tempRoutes
})
}