You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React父组件向子组件传递数组props不生效问题排查

问题修复方案

你的代码存在3个直接导致运行异常的问题:

  • App组件内未定义teams数组就直接向子组件传递,会触发teams is not defined引用错误
  • Standings是函数式组件,不存在类组件的this实例,且你未在组件参数中接收父组件传入的props,this.teams无法取到任何值
  • 数组遍历时将单条队伍数据的参数命名为teams,和外层数组名重名,易引发语义混淆,建议修改为语义化命名

修正后的App.js

你需要先在App作用域内定义/获取到teams数据源,再向子组件传递,静态数据可直接声明,动态接口数据建议结合useState、useEffect管理:

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Navbar from './Navbar';
import Home from './Home';
import Teams from './Teams';
import Standings from './Standings';

// 替换为你实际的teams数组数据,动态场景可改用useState存储
const teams = [
  // 示例数据结构,替换为你的真实内容即可
  // { team: "队伍A", wins: 12, loss: 1, streak: "5连胜", pf: 380, pa: 120, pd: 260, logo: "/logo/a.png" }
];

function App() {
  return (
    <Router>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/teams" element={<Teams />} />
        <Route path="/standings" element={<Standings teams={teams}/>} />
      </Routes>
    </Router>
  )
}

export default App;

修正后的Standings.js

函数组件通过入参接收父组件传递的props,直接调用传入的teams数组做遍历即可,移除错误的this引用,调整遍历单条数据的命名避免冲突:

// 提前引入你代码中用到的logo资源,注意如果logo存在teams数据里,直接取单条数据的logo字段即可
// import defaultLogo from './assets/default-logo.png';
const Standings = ({ teams }) => { // 解构接收传入的teams属性
    return (
        <div className='cont'>
            <table className='content-table'>
            <caption>American Football Federation Standings - Season 3</caption>
                <thead>
                    <tr>
                        <th>Rank</th>
                        <th>Team</th>
                        <th>W</th>
                        <th>L</th>
                        <th>Streak</th>
                        <th>PF</th>
                        <th>PA</th>
                        <th>P+/-</th>
                    </tr>
                </thead>
                <tbody>
                    {teams.map((team, i) => {
                        return (
                            <tr key={i}>
                                <td>{i+1}</td>
                                <td><img src={team.logo} width="30px"/>{team.team}</td>
                                <td>{team.wins}</td>
                                <td>{team.loss}</td>
                                <td>{team.streak}</td>
                                <td>{team.pf}</td>
                                <td>{team.pa}</td>
                                <td>{team.pd}</td>
                            </tr>
                        );
                    })}
                </tbody>
            </table>
        </div>
    )
}

export default Standings;

补充:如果后续需要在任意组件都能访问teams数组、不想逐层传递props,可以接入React Context做全局状态共享,当前修复完成后页面即可正常渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 13:48:19