当存储状态更改时,反应 Redux 工作意外



我很困惑。

我正在为我的容器使用 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)

此代码的奇数部分如下。

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

但!!

当存储中的后状态更改时,后容器状态也会更改

为什么???

即使我没有在componentWillReceiveProps中处理新数据.

谢谢。。。

只需稍作更改,您的代码将按预期工作

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);

最新更新