从对象数组中选择特定索引

问题描述 投票:0回答:1

我正在做一个axios调用,我收到的数据是来自后端的对象数组,每个对象都包含一个名为result的值(格式 - 结果:“Hello”)。有一个按钮,当单击时应转到特定索引并获取指定结果的值并传递它。不确定如何完成这一点。

componentDidMount(){
let payload = this.props.location.state
axios.post(`http://localhost:8200/service/${this.service_name}/requests`,payload)
  .then( response=>{
    console.log(response.data.methods)
    this.setState({
      methods:response.data.methods,
      trace:response.data.methods[0].result  
      // Here above i have written ,but it only fetches from index[0] statically , 
        i want it to select the result of the particular button i press. 
    });
  })
 }
 playitHandler(){
  let payload = {
  "service_name":this.service_name,
  "trace_id":this.state.trace
  }
 }
 <button className="btn btn-primary" onClick={()=>this.playitHandler()}>Display</button>

尝试将索引传递给ComponentDidMount(){},我想我们不能将它传递给那里,因为它抛出了一个错误。

arrays reactjs
1个回答
1
投票

什么时候必须完成提取?因为,如果在加载页面时执行该操作,则在按下按钮时无法检索特定数据。据我所知,你有两种可能:

  1. 制作一个retrieveIndexData()函数,它在一个按钮上输入click事件。在此函数内部运行axios调用,然后使用parseInt(ev.target.value)将数据保存在索引中。虽然,我认为这不是最好的做法;
  2. 在状态中添加属性selectedIndex,并且在单击按钮时,将相对索引保存在该属性中。相反,在axios调用中,您保存所有索引。然后,您可以使用this.state.trace[this.state.selectedIndex]处理您选择的数据,单击按钮;

编辑:让我更好地解释第二点。在该州,您拥有属性response.data.methods,您可以在其中保存methods数组的所有元素,包括您要在州的trace属性中保存的元素。

现在,因为你只是在州内创建冗余,在那个setState我只会写:this.setState({ methods: response.data.methods })。你现在拥有州内所需的一切!

最后,我认为你展示的button元素只是一个“0按钮”,如果你按下,你需要第一种方法。所以我猜你还有第二个按钮,你考虑第二个元素,依此类推。如果这是正确的,那么我应该期待这样的事情:

<button className="btn btn-primary" onClick={() => this.playitHandler(0)}Display 0</button>
<button className="btn btn-primary" onClick={() => this.playitHandler(1)}Display 1</button>
...
<button className="btn btn-primary" onClick={() => this.playitHandler(100)}Display 100</button>

假设我是对的,然后在playitHandler()你可以浏览this.state.methods来检索你想要的东西:

playitHandler(methodIndex) {
    let payload = {
        "service_name": this.service_name,
        "trace_id": this.state.methods[methodIndex]
    }
}

它更清楚了吗?我避免在这个例子中使用selectedIndex属性,但是,我认为这种方式更简单。

© www.soinside.com 2019 - 2024. All rights reserved.