You need to enable JavaScript to run this app. React.js 如何从接口返回的数组获取唯一点击数据并实现页面跳转
优惠活动
大模型
产品
解决方案
定价
更多

React.js 如何从接口返回的数组获取唯一点击数据并实现页面跳转

核心问题定位

当前代码无法识别点击条目的原因有三个硬伤:

  • 子列表渲染时,onClick绑定传入的索引变量i未在map回调中声明,实际传递值为undefined
  • 点击处理函数仅接收浏览器事件对象,没有把当前遍历到的完整用户数据作为参数传入,断开了数据传递链路
  • 因为没有绑定具体条目的上下文参数,事件触发后只能执行通用日志打印,无法关联到具体的用户条目
实现思路
  1. 补全事件传递链路:在users.map遍历过程中,同时拿到当前用户对象和对应的索引值,在绑定点击事件时,把这两个值作为参数传给点击处理函数
  2. 调整事件处理函数的参数顺序:接收传入的用户数据、索引值,最后再接React合成事件对象,保留阻止冒泡的逻辑,避免触发外层列表项的折叠/展开逻辑
  3. 接入跳转逻辑:拿到完整的选中用户数据后,结合项目使用的路由方案做页面跳转,把选中的数据传递给目标页面
修正后的参考代码
class App extends React.Component {
  constructor(){
    super();
    this.state = {
      showItems: [],
      users: []
    }
  }

  onClick(index){
    console.log('its clicked')
    let showItems = this.state.showItems.slice(0);
    showItems[index] = !showItems[index];
    this.setState({showItems});

    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then(response => {
        console.log(response);
        this.setState({ users: response.data });
      })
      .catch(error => {
        console.log(Error);
        this.setState({ errorMsg: "Wrong API call !!!" });
      });
  }

  // 调整参数顺序:先接收自定义传入的用户数据、索引,最后接收事件对象
  handleNest = (selectedUser, index, event) => {
    event.stopPropagation()
    console.log('i got a click', '选中条目数据:', selectedUser, '条目索引:', index)

    // 跳转逻辑示例(以React Router为例)
    // this.props.history.push({
    //   pathname: '/user-detail',
    //   state: {
    //     userInfo: selectedUser // 把选中的完整用户数据传到目标页面
    //   }
    // })
  }

  render() {
    const { users } = this.state;
    return (
      <div className="App">
        <ul>
          <li onClick={this.onClick.bind(this, 0)}>
            item {this.state.showItems[0] ? 
              <div> 
                {users.length ? 
                  // 补充map的索引参数,修正事件绑定的传参
                  users.map((user, index) => (
                    <div
                      style={{
                        padding: "10px",
                        color: "blue",
                        textTransform: "initial"
                      }}
                      onClick={this.handleNest.bind(this, user, index)}
                      key={user.id}
                    >
                      {user.name}
                    </div>
                  ))
                : null} 
              </div> 
            : null} 
          </li>
        </ul>
        <div style={{marginTop: 100}}>*click on item to open submenu</div>
      </div>
    );
  }
}

export default App;
注意事项
  • 如果使用bind在渲染函数中绑定事件,参数顺序必须和事件处理函数的参数定义保持一致,React的合成事件对象会作为最后一个参数自动传入
  • 如果不想在路由状态里存完整用户数据,也可以把用户id拼在跳转路径中,目标页面根据id请求对应详情,适合数据量较大的场景
  • 目标页面可以通过路由提供的接口直接读取上一页传入的用户数据,不需要重复请求列表接口

内容的提问来源于stack exchange,提问作者Mercy Kannan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.01 13:15:01