【发布时间】:2021-10-10 01:00:15
【问题描述】:
您好,我是 React 的新手(第 2 天)。我只是想将状态从一个组件传递到另一个组件,但我一直在努力寻找一个以我的项目结构方式处理这个问题的教程(我想我的项目结构非常糟糕......)。我在 codeSandbox 上上传了可重现的代码:codesandbox.io/s/dreamy-maxwell-q83lc
我的代码
我的App.js 目前看起来像这样。我通过不同的 url 访问组件屏幕。
import componentOne from "./componentOne"
import componentTwo from "./componentTwo"
function App() {
return (
<div>
<Router>
<Switch>
<Route path = "/componentOne">
<componentOne/>
</Route>
<Route path = "/componentTwo">
<componentTwo/>
</Route>
</Switch>
</Router>
</div>
)
}
export default App
我想将状态从componentOne 传递到componentTwo。这是我的componentOne.jsx 文件。通过单击图像,URL 会发生变化,因此我位于 componentTwo 页面。但我不确定如何以这种方式将状态从componentOne 传递给它。
import {useState, useEffect} from "react";
function componentOne() {
const [stateOne, setStateOne] = useState(null)
const [stateTwo, setStateTwo] = useState(null)
const [stateThree, setStateThree] = useState(null)
/**
* API call that populates stateOne, stateTwo and stateThree
*/
return (
<div>
{/*I want to pass stateOne to componentTwo*/}
<a href="/componentTwo">
<img src = {stateOne.image} alt={""}/>
</a>
{/*I want to pass stateTwo to componentTwo*/}
<a href="/componentTwo">
<img src = {stateTwo.image} alt={""}/>
</a>
{/*I want to pass stateThree to componentTwo*/}
<a href="/componentTwo">
<img src = {stateThree.image} alt={""}/>
</a>
</div>
)
}
export default componentOne
这是我的componentTwo.jsx 文件。请注意,我要传递给componentTwo 的数据是 JSON。
function componentTwo(props) {
// I want my JSON data to be in props
return(
// I then want to use this JSON data to display things
<text> {props.title} </text>
)
}
export default componentTwo
到目前为止我已经尝试过什么
到目前为止,我已经从App.js 中删除了componentTwo 路由路径,并以这种方式将其添加到componentOne,但它似乎不起作用。
function componentOne() {
return (
<div>
...
<Router>
<Switch>
<Route path = "/componentTwo">
<componentTwo recipe={stateThree}/>
</Route>
</Switch>
</Router>
<a href="/componentTwo">
<img src = {stateThree.image} alt={""}/>
</a>
</div>
)
}
【问题讨论】:
标签: reactjs react-hooks react-router