【发布时间】:2019-11-06 01:19:06
【问题描述】:
我想将 prop productId 从 home 组件传递给 main 组件。
导航到新组件时如何传递一些初始状态
主页组件
let productId = "123" // get from query string
return (
<Button className="startButton"
variant="contained"
color="primary"
component={Link} to="/main"
fullWidth>
Start
</Button>
)
主要组件
export class Main extends Component {
constructor(props) {
super(props);
this.state = {
productId: "",
}
}
}
然后在我的主要组件中,我可以设置该 productId 的状态。
路由器
const Router = () => {
return (
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path="/main" component={Main} />
</Switch>
)
}
export default Router;
我正在使用以下库 https://reacttraining.com/react-router/web/guides/quick-start
更新: https://reacttraining.com/react-router/web/guides/basic-components/route-rendering-props
您可以在这里看到该示例传递了一些额外的属性someVariable 我希望能够做到这一点。
【问题讨论】:
-
你的组件是如何相互连接的?
-
我不认为我理解这个问题。我有一个路由器文件,我在其中声明了所有 url,以及应该根据确切路径呈现的组件。然后在我的主组件中,我使用反应路由器链接根据 url
component={Link} to="/main"导航到主组件,这有帮助吗? -
如果它们没有以任何方式连接,那么
redux是在组件之间传递数据的正确方式 - redux.js.org -
我已经在使用 redux
-
因为你已经在使用
redux,你可以在reducer中维护productId,在你的查询被执行时,从主组件调度更新productId的操作,将你的主组件连接到redux 商店,现在您可以在导航到同一组件时更新主组件中的值。