我有两个不同的项目,其中一个我正在使用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。组件接收的道具是mapStateToProps道具与您直接传递的道具的组合。在某些情况下,具有局部组件状态是有意义的,但是使用connect组件的原因之一是避免这种情况,而是将所有内容存储在全局状态中,在全局状态中通过分派操作而不是调用。关于问题的更新,似乎在类上调用setState破坏了connect的工作方式,因此您可能应该只在构造函数中初始化状态。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))
09-16 08:03
查看更多