Javascript TypeError:无法读取属性';bio&x27;未定义的
所以我一直在尝试用ReactJs实现一个编辑表单,我遇到了一个错误“TypeError:Cannotreadproperty'bio'ofUndefined” 我做了几个小时的研究,他们建议添加一个构造函数,但即使这样也无法修复它 以下是我的EditForm.js的部分代码:Javascript TypeError:无法读取属性';bio&x27;未定义的,javascript,reactjs,Javascript,Reactjs,所以我一直在尝试用ReactJs实现一个编辑表单,我遇到了一个错误“TypeError:Cannotreadproperty'bio'ofUndefined” 我做了几个小时的研究,他们建议添加一个构造函数,但即使这样也无法修复它 以下是我的EditForm.js的部分代码: const styles = (theme) => ({ ...theme.spreadThis, button: { float: 'right' } }); class EditForm e
const styles = (theme) => ({
...theme.spreadThis,
button: {
float: 'right'
}
});
class EditForm extends Component {
state = {
bio: '',
website: '',
location: '',
open: false
};
constructor(props){
super(props);
this.setState = this.setState.bind(this);
}
mapUserDetailsToState = (credentials) => {
this.setState({ //here is the problem
bio: credentials.bio ? credentials.bio : '',
website: credentials.website ? credentials.website : '',
location: credentials.location ? credentials.location : ''
});
};
componentDidMount() {
const { credentials } = this.props;
this.mapUserDetailsToState(credentials);
}
render() {
const { classes } = this.props;
return (
<Fragment>
<MyButton
tip="Edit Details"
onClick={this.handleOpen}
btnClassName={classes.button}
>
<EditIcon color="primary" />
</MyButton>
<Dialog
</Fragment>
);
}
}
EditForm.propTypes = {
editUserDetails: PropTypes.func.isRequired,
classes: PropTypes.object.isRequired
};
const mapStateToProps = (state) => ({
credentials: state.user.credentials
});
export default (withStyles(styles)(EditForm));
const styles=(主题)=>({
…主题。传播这个,
按钮:{
浮动:“对”
}
});
类EditForm扩展组件{
状态={
个人简历:'',
网站:'',
位置:“”,
开放:假
};
建造师(道具){
超级(道具);
this.setState=this.setState.bind(this);
}
mapUserDetailsToState=(凭据)=>{
this.setState({//问题出在这里
bio:credentials.bio?credentials.bio:“”,
网站:credentials.website?credentials.website:“”,
位置:凭据。位置?凭据。位置:“”
});
};
componentDidMount(){
const{credentials}=this.props;
此.mapUserDetailsToState(凭据);
}
render(){
const{classes}=this.props;
返回(
({
凭据:state.user.credentials
});
导出默认值(使用样式(样式)(EditForm));
有人知道怎么修吗
编辑:这是错误的屏幕截图
看起来props中的凭证对象未定义。因此出现错误
未定义。bio
(无法读取未定义的bio属性)
在访问凭证的任何属性之前,请确保凭证可用
if (credentials !== undefined && credentials !== null) {
// do your stuff
}
您的状态应该在
constructor
内部和super
constructor(props) {
super(props);
this.state = {
bio: '',
website: '',
location: '',
open: false
};
this.setState = this.setState.bind(this);
}
你首先需要检查
凭证
是否存在,然后你必须检查凭证.bio
是否存在,因为检查未定义。bio
没有意义。你的道具没有获得凭证,因此被视为未定义。在chrome devel中的MapStateTops
上设置断点操作工具来找出状态对象中的内容。但这样做会得到“状态未定义”现在我添加了this.state,最初我错过了它,现在你能检查一下吗?抱歉,但同样的问题:/你能分享屏幕截图或其他东西吗?因为状态和函数必须在react中包装在constructor中。我的意思是this.state没有解决这个问题凭据有smth错误,但我找不到它,正如你所说的,它忽略了if中的代码声明,意味着凭据不可用,那么我该怎么办?抱歉,我还是JS的初学者,所以我不知道具体的工作原理,您需要检查为什么凭据不可用,以及导致此问题的父组件中可能存在的问题。如果父组件中的所有凭据都很好,那么您需要检查凭据在su中是否可用b顺序渲染。您可以使用componentdiddupdate
来执行此操作。如果您可以在演示版本中发布链接(codesandbox或类似内容),则调试将非常有用。