当存储状态发生变化时,react redux 会意外工作

问题描述 投票:0回答:1

我很困惑。

我正在为我的容器使用react-redux

我的代码如下

import React from 'react'
import { connect } from 'react-redux'

const mapStateToProps = (state) => ({
    post : state.post
})

const PostContainer extends Component {
    constructor(props){
       super(props)
       this.state = {
           post : props.post
       }
    }

    render(){
          <div>
               {post.title}
          </div>
    }
}

export default connect(mapStateToProps, null)(PostContainer)

这段代码的奇怪部分如下。

现在在我的代码中,我只获取第一个构造中的状态,然后我没有获取该状态中的新数据。

但是!!

当 store 中的 postState 改变时,PostContainer State 也会改变

为什么???

即使我没有在

componentWillReceiveProps
中处理新数据。

谢谢你...

reactjs redux containers state react-redux-connect
1个回答
1
投票

只需进行少量更改,您的代码就会按预期工作

import React, { Component } from 'react';
import { connect } from 'react-redux';

class PostContainer extends Component {
  render() {
    return (
       <div>{this.props.post.title}</div>;
    ) 
  }
}

const mapStateToProps = state => ({
  post: state.post
});

export default connect(mapStateToProps)(PostContainer);
© www.soinside.com 2019 - 2024. All rights reserved.