【发布时间】:2020-11-12 23:17:21
【问题描述】:
第一个帖子和新的反应。
我遇到了一个问题,当我尝试在渲染外部的函数中使用 prop 时,它是 undefined,而当我尝试使用它来设置状态值时,它不起作用。
我已经阅读并找到了很多答案,主要是所有函数都应该绑定到类或使用箭头方法,所以当在函数内部引用this 时,它指的是类。
这些似乎都不起作用。
任何帮助将不胜感激。
下面是我正在使用的代码。
我从另一个组件调用EntryForm 组件,传递userDetails.Id 中的值5。
export interface UserDetails {
Id: string;
}
export interface IProps {
userDetails: UserDetails
}
export interface IState {
combinedURL: string;
}
export default class EntryForm extends React.Component<IProps, IState> {
constructor(props : IProps) {
super(props);
this.state = {
combinedURL: 'MonkeyFace12' as string
};
this.createCombinedURL = this.createCombinedURL.bind(this);
}
async createCombinedURL() {
try {
this.setState({ combinedURL: 'This is the Start of the URL followed by ' + this.props.userDetails.Id });
} catch (e) {
console.log("Error setting CombinedURL");
}
}
async componentDidMount() {
try {
await this.createCombinedURL();
} catch (error) {
}
}
render() {
return (
<>
<FormGroup row>
<Label
sm={1}>
Client
</Label>
</FormGroup>
<Button color="primary" type="submit">
Sign in
</Button>
</>
);
}
}
当我检查 this.state.CombinedURL 的值时,它仍然是 MonkeyFace12。
函数CreateCombinedURL 似乎完全没有影响。
【问题讨论】:
-
所以如果我正确地让你说当你调用 this.setate 时它不起作用?最后,如果您是 React 新手,为什么不使用纯 JavaScript,直到您对 React 感到满意,而不是添加 TypeScript。
-
您好,非常感谢您的回复。是的,当它运行命令时 this.setState({ combinedURL: '这是 URL 的开始,后跟 ' + this.props.userDetails.Id });它不设置组合 URL 状态。它保持为 MonkeyFace12。同样在调试期间,this.props.userDetails.Id 的计算结果为“未定义”。
-
我明白你在说什么,但是当你刚接触 React 时,建议不要尝试将 TypeScript 添加到你只是让自己陷入困境的组合中
标签: reactjs typescript state this react-props