javascript - 为 React 中的每个元素制作独特的 NavLink 很热?
问题描述
我有一些问题。我从本地 Json 文件中获取一个数组并将其放入本地状态。下面,你可以看到我在哪里使用map来显示来自 array phone的所有模型。当我单击其中一个时,它会创建具有特殊 ID(包含在数组中)的新链接。我的Route在 App 组件中,但这个NavLink在Shop Component中。(你可以在下面看到)
const App = () => {
return (
<div >
<Header />
<div>
<Route path="/LogIn" render={() => <LogIn />} />
<Route path="/Shop" render={() => <Goods />} />
<div>
<Route path="/CurrentIphone" render={() => <CurrentIphone />} />
</div>
</div>
</div>
)
}
所以,我不知道如何创建具有唯一参数的组件CurrentIphone 。当用户单击其中之一时,用户必须只看到响应其ID的参数(价格、型号等)
class Iphone extends React.Component {
constructor(){
super();
this.state = {
phone: []
}
}
//put domain's title to prevent circular dependency on windows
//domain's title 'MyWebShop/'
componentDidMount() {
getPhone.then(({data}) => {
this.setState({
phone: data
})
})
}
render() {
return(
<div>
{this.state.phone.map((p,index) => (
<div className='model' key={index}>
<NavLink to={'/CurrentIphone' + p.id}>{p.body.model}</NavLink>
</div>))}
</div>
)
}
}
export default Iphone;
解决方案
我不太确定你的问题是什么,或者你为什么要为 iPhone 使用类组件。据我了解,您需要一条动态路线。
<Route path="/CurrentIphone" render={() => <CurrentIphone />} />
应该
<Route path="/CurrentIphone/:id" render={() => <CurrentIphone />} />
PS,传递孩子而不是渲染是首选方式。
<Route path="/CurrentIphone/:id">
<CurrentIphone />
</Route>
此外,您似乎缺少一个“/”。
<NavLink to={'/CurrentIphone' + p.id}>{p.body.model}</NavLink>
很可能需要
<NavLink to={'/CurrentIphone' + p.id}>{p.body.model}</NavLink>
或使用模板文字
<NavLink to={`/CurrentIphone/{p.id}`}>{p.body.model}</NavLink>
好的,我将进一步扩展我的答案。
您的 CurrentIphone 组件应该看起来像这样。
顺便说一句,我假设您没有使用打字稿。
const CurrentIPhone = ({ match }) =>{
// the match prop and id that we destructure from it is there because you
// used the Route component with the path "CurrentPhone/:id"
const { params } = match;
const { id } = params;
// all this nasty match params id stuff can be avoided if you just use
// the new react router hooks.
// if that was the case, you wouldn't destructure any props
// you would just use
let { id } = useParams()
const [deviceList, setDeviceList] = useState([])
// get the list of all the devices and store it in state, as you did in
// the other iphone component
useEffect(()=>{
getPhone.then(({ data }) => {
setDeviceList(data)
})
}, [])
// take the array of all devices and the id you have from the match prop
// and get the device by comparing the two id's
const chosenDevice = deviceList && deviceList.filter(el=>el.id===id)
return(
<div>{chosenDevice && chosenDevice.name}</div>
)
}
不要忘记从 react 中导入 useEffect 和 useState
推荐阅读
- java - 如何使用 Java Azure Functions 解析 JSON 并插入到 Azure SQL
- date - 如何编写视图以识别具有日期字段的内容而不重复
- c# - 标签助手 - Razor View asp net core
- vulkan - Vulkan - 渲染成多平面 YUV 渲染目标
- mapbox - 使用 mapbox GL Js 添加多个 geoJSON 源
- google-chrome - xPath 不能通过 id 选择包含
- bash - Gitignore 忽略没有文件扩展名的 bash 脚本
- c# - How do I migrate my code from .Net Framework to .Net Core 3.1?
- java - 在 Maven 构建期间包 io.rsocket.core 不存在
- javascript - 如何使用js获取特定时区的最后一天的日期