React函数组件报错:无法读取location属性,求解决方案
为什么箭头函数组件中无法读取
this.props.location.roleAction? 问题原因
在类组件里,React会自动把props绑定到组件实例的this上,所以你能通过this.props访问传入的属性。但函数式组件(包括箭头函数组件)没有自己的this上下文,这里的this本质是undefined,自然就会抛出cannot read property 'location' of undefined的错误。
修复方案
函数式组件的props是作为参数直接传入的,你只需要把props作为箭头函数的参数,直接访问即可,完全不需要用this:
方案1:直接接收props参数
const User = (props) => ( <Aux> <UserTable title="User" type="user" role={props.location.roleAction} /> </Aux> ); export default User;
方案2:解构props(更简洁)
如果只需要用到location这一个属性,还可以直接解构参数,让代码更清爽:
const User = ({ location }) => ( <Aux> <UserTable title="User" type="user" role={location.roleAction} /> </Aux> ); export default User;
最后提个小细节:React组件的命名规范是首字母大写(比如User而非user),这样React才能正确识别它是自定义组件,而不是普通HTML标签~
内容的提问来源于stack exchange,提问作者Satria stuart
相关产品推荐
相关产品推荐

