首页 > 解决方案 > 为 React 中的每个元素制作独特的 NavLink 很热?

问题描述

我有一些问题。我从本地 Json 文件中获取一个数组并将其放入本地状态。下面,你可以看到我在哪里使用map来显示来自 array phone的所有模型。当我单击其中一个时,它会创建具有特殊 ID(包含在数组中)的新链接。我的Route在 App 组件中,但这个NavLinkShop 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;

标签: javascriptreactjs

解决方案


我不太确定你的问题是什么,或者你为什么要为 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


推荐阅读