我有两个不同的项目,其中一个我使用 Redux,我的组件声明为:
class Foo extends React.component<any, any> {
public static state: any = {
bar: ''
}
}
const mapStateToProps = (state) => {
return {}
}
export default connect(mapStateToProps)(withRouter(Foo))
然后我有一个没有 Redux 的不同项目,其中我的组件声明为:
class Foo extends React.Component<any, any> {
public static state: any = {
bar: ''
}
}
export default Foo;
我尝试在 redux 项目上以静态方式声明我的状态,但它根本没有在运行时被拾取,有人可以给我一个解释吗?
编辑:
看来我的问题不够清楚,更多代码来澄清:
class Foo extends React.component<any, any> {
public static state: any = {
bar: ''
}
render() {
console.log(this.state); // null <- why?
return (...);
}
}
const mapStateToProps = (state) => {
return {}
}
export default connect(mapStateToProps)(withRouter(Foo))
而非 redux 代码:
class Foo extends React.Component<any, any> {
public static state: any = {
bar: ''
}
render() {
console.log(this.state) // { bar: '' } <- works! why?
return (...)
}
}
export default Foo;
最佳答案
函数 mapStateToProps
不会设置组件的状态,它会将部分应用程序状态(在 Redux 存储中)映射到组件的 props。
您的组件接收的 props 是来自 mapStateToProps
的 props 和您直接传递的 props 的组合。
在某些情况下,拥有本地组件状态是有意义的,但使用connect
组件的原因之一是避免这种情况,而是将所有内容存储在全局状态中,并在全局状态中进行更新通过分派(dispatch)操作,而不是调用 setState
。
引用您的问题的更新,看起来在您的类上调用 connect
破坏了 static
的工作方式,因此您可能应该在构造函数。
class Foo extends React.component<any, any> {
constructor() {
this.state = {
bar: ''
};
}
render() {
console.log(this.state); // null <- why?
return (...);
}
}
const mapStateToProps = (state) => {
return {}
}
export default connect(mapStateToProps)(withRouter(Foo))
关于javascript - Typescript和jsx,为什么对象生命周期中静态声明的状态为null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44066551/