React中如何正确使用componentDidMount与componentDidUpdate解决indexOf报错
报错根因
- 访问
carData的路径错误:carData存储在组件state中,原代码直接写this.carData实际取到的是undefined,调用indexOf方法直接触发报错。 - 生命周期逻辑缺陷:
componentDidUpdate未加触发条件,调用setState后会反复触发更新形成死循环- 请求拿到
carData后没有主动执行索引计算,首次加载时id始终为初始值null
- 缺少边界校验:未处理未匹配到对应品牌的场景,容易出现后续渲染报错。
修复后完整代码
class CarPage extends Component { state = { isLoading: true, carData: [], id: null } findMyIndex = () => { // 正确从state中取carData,增加边界判断 const targetIndex = this.state.carData.indexOf(this.props.brand); this.setState({ id: targetIndex >= 0 ? targetIndex : null }) } componentDidUpdate(prevProps) { // 仅当props.brand发生变化时才重新计算索引,避免死循环 if (prevProps.brand !== this.props.brand) { this.findMyIndex(); } } componentDidMount() { fetch("/data.json") .then(response => response.json()) .then(data => { this.setState({ carData: data, isLoading: false, // 数据加载完成后主动计算索引 }, this.findMyIndex) }) } render() { // 增加id合法性判断,避免取值报错 return ( <> {!this.state.isLoading && this.state.id !== null && ( <p>{this.state.carData[this.state.id].model}</p> )} {!this.state.isLoading && this.state.id === null && ( <p>未找到对应品牌的车型信息</p> )} </> ); } } export default CarPage;
关键修改说明
- 修正
carData取值路径:统一通过this.state.carData访问存储的车辆数据 - 优化
componentDidUpdate逻辑:仅在props.brand发生变化时才重新计算索引,避免死循环 - 补充数据加载后的执行逻辑:
setState的第二个参数传入回调函数,确保carData赋值完成后再计算索引 - 增加边界校验:对索引不存在的场景做兼容处理,避免渲染报错
内容的提问来源于stack exchange,提问作者D A R K VerbalCentaurPL
相关产品推荐
相关产品推荐

