从反应中的数组中选择一个特定的索引

时间:2019-02-27 03:07:27

标签: reactjs

我正在进行axios调用以通过更新状态来获取某些数据并将该数据存储在称为url的列表中,但是,当我单击列表中的任何特定项时,应该获取该对应的索引以便我可以存储处于状态并将其传递到子组件。不知道如何精确地做到这一点。

constructor(props){
   super(props);
   this.state={
     urls:[],
     selectedUrl : ''
    }
  }
componentDidMount(){
axios.get(`http://localhost:8200/service/${this.service_name}`)
  .then(  response=> {
    console.log(response.data);
    this.setState({
      urls:response.data.urls
    })
  })
}

selectedUrlHandler(i){
   console.log('before clicked',i,this.state)
   this.setState((state)=>({
      selectedUrl:state.urls[i]
       }) , ()=>{ console.log(this.state.selectedUrl)});
   console.log('after clicked',i,this.state)
}

render(){
   return(
       {
            this.state.urls.map( (list,i) => {
              return(
                <tr key={index}>
                <td>
                    <Link to={{pathname:`/service/${this.service_name}/requests`, 
                                state:{url:this.state.selectedUrl}}} 
                                onClick={()=>this.selectedUrlHandler(i)}>{list}</Link>
                </td>
                </tr>
              );
            })
          }
    )
}

如上所述,我要获取被单击的特定项目的索引并更新selectedUrl状态。

从屏幕快照中可以看到,根本无法访问setState内的console.log。 enter image description here

任何帮助表示感谢,谢谢。

1 个答案:

答案 0 :(得分:0)

您有两种可能的解决方案:

  1. 使用history.push动态更改路线。相反,您可以使用li并在li上定义onClick事件。
  2. state:{url:this.state.selectedUrl}更改为state:{url: this.state.urls[i]}

在第一个解决方案中,链接已经具有用于单击的内部处理程序,该处理程序将重定向到另一个路由。因此,如果需要在其上使用onClick,则需要

<Link 
    to="/item" 
    onClick={(e) => this.changeRoutePath(e)}>
    Prevent 
</Link>

changeRoutePath(e){
    e.preventDefault();
    this.props.history.push(this.props.match.path);
}

在第二种解决方案中,由于您映射了所有URL,因此可以直接将索引传递给this.state.urls[i]以获取当前URL。

希望有帮助。

相关问题