React+Redux开发报Cannot read properties of undefined(reading 'props')错误
错误排查及修复方案
错误根源
你定义的shop是React函数式组件,这类组件不存在this实例上下文,代码中调用this.props.numOfLaptops时,this的取值为undefined,因此直接抛出读取props属性失败的报错。
修复方案
方案1:函数组件原生写法(推荐)
直接在函数组件的入参位置接收connect注入的props即可,有两种常用写法:
全量接收props
import React from "react"; import { connect } from "react-redux"; import "./style.css"; // 入参接收props const shop = (props) => { return ( <div> <h1 className="title">Welcome to Vshop</h1> <div className="item"> <p>Apple Macbook Air</p> {/* 直接用props调用,不需要加this */} <p>Available: {props.numOfLaptops}</p> <button>Buy Now</button> </div> </div> ); }; const mapStateToProps = (state) => { return { numOfLaptops: state.numOfLaptops, }; }; export default connect(mapStateToProps, null)(shop);
解构props简化代码
如果只需要用到numOfLaptops这一个属性,可以直接在入参位置解构:
// 直接解构出注入的属性 const shop = ({ numOfLaptops }) => { return ( <div> <h1 className="title">Welcome to Vshop</h1> <div className="item"> <p>Apple Macbook Air</p> {/* 直接使用解构出的变量 */} <p>Available: {numOfLaptops}</p> <button>Buy Now</button> </div> </div> ); };
方案2:改为类组件兼容this.props写法
如果想要沿用this.props的调用方式,需要将函数组件改为类组件:
import React from "react"; import { connect } from "react-redux"; import "./style.css"; class Shop extends React.Component { render() { return ( <div> <h1 className="title">Welcome to Vshop</h1> <div className="item"> <p>Apple Macbook Air</p> <p>Available: {this.props.numOfLaptops}</p> <button>Buy Now</button> </div> </div> ) } } const mapStateToProps = (state) => { return { numOfLaptops: state.numOfLaptops, }; }; export default connect(mapStateToProps, null)(Shop);
内容的提问来源于stack exchange,提问作者somutesting
相关产品推荐
相关产品推荐

