gpt4 book ai didi

javascript - 热衷于为 React 中的每个元素制作唯一的 NavLink?

转载 作者:行者123 更新时间:2023-12-02 20:48:50 27 4
gpt4 key购买 nike

我有一些问题。我从本地 Json 文件获取一个数组并将其放入本地状态。下面,您可以看到我在哪里使用 map 来显示数组手机中的所有型号。当我单击其中之一时,它会创建带有特殊 id 的新链接(包含在数组中)。我的路线位于应用程序组件中,但此NavLink位于商店组件中。 (您可以在下面看到)

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 组件应如下所示。

顺便说一句,我假设您没有使用 typescript 。

  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

关于javascript - 热衷于为 React 中的每个元素制作唯一的 NavLink?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61666263/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com