Javascript Typescript和jsx,为什么静态声明的状态在对象的生命周期中为空?
我有两个不同的项目,其中一个使用Redux,我的组件声明为:Javascript Typescript和jsx,为什么静态声明的状态在对象的生命周期中为空?,javascript,reactjs,typescript,redux,Javascript,Reactjs,Typescript,Redux,我有两个不同的项目,其中一个使用Redux,我的组件声明为: class Foo extends React.component<any, any> { public static state: any = { bar: '' } } const mapStateToProps = (state) => { return {} } export default connect(mapStateToProps)(withRouter(Foo)) clas
class Foo extends React.component<any, any> {
public static state: any = {
bar: ''
}
}
const mapStateToProps = (state) => {
return {}
}
export default connect(mapStateToProps)(withRouter(Foo))
class Foo extends React.Component<any, any> {
public static state: any = {
bar: ''
}
}
export default Foo;
类Foo扩展React.component{
公共静态:任意={
栏:“”
}
}
常量mapStateToProps=(状态)=>{
返回{}
}
导出默认连接(MapStateTops)(带路由器(Foo))
然后我有一个没有Redux的不同项目,其中我的组件声明为:
class Foo extends React.component<any, any> {
public static state: any = {
bar: ''
}
}
const mapStateToProps = (state) => {
return {}
}
export default connect(mapStateToProps)(withRouter(Foo))
class Foo extends React.Component<any, any> {
public static state: any = {
bar: ''
}
}
export default Foo;
类Foo扩展了React.Component{
公共静态:任意={
栏:“”
}
}
导出默认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))
类Foo扩展React.component{
公共静态:任意={
栏:“”
}
render(){
console.log(this.state);//null{
返回{}
}
导出默认连接(MapStateTops)(带路由器(Foo))
鉴于非重复代码:
class Foo extends React.Component<any, any> {
public static state: any = {
bar: ''
}
render() {
console.log(this.state) // { bar: '' } <- works! why?
return (...)
}
}
export default Foo;
类Foo扩展了React.Component{
公共静态:任意={
栏:“”
}
render(){
console.log(this.state)/{bar:''}函数mapstatetops
不设置组件的状态,它将应用程序状态的一部分(在redux存储中)映射到组件的道具
组件接收的道具是来自mapStateToProps
的道具和您直接传递的道具的组合
在某些情况下,使用本地组件状态是有意义的,但使用connect
ed组件的原因之一是为了避免这种情况,而是将所有内容存储在全局状态中,在全局状态中通过调度操作更新,而不是调用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))
类Foo扩展React.component{
构造函数(){
此.state={
栏:“”
};
}
render(){
console.log(this.state);//null{
返回{}
}
导出默认连接(MapStateTops)(带路由器(Foo))
请检查更新的问题,似乎我对以不同方式声明时未设置状态的问题不够清楚。道具很好,我知道如何使用connect和mapDispatchToProps,这是状态声明让我困惑。我更新了我的答案,很抱歉,我无法提供更好的解释,但我认为不管怎样,这就是解决方案。是的,我知道只要在构造函数上声明状态就行了,谢谢!