我使用redux并且我的应用程序无法检测到状态更改。
这是我的redux数据模型:
allPosts
-post{key,body}
-comments
-comment{key,body}
-comment{key,body}
-comment{key,body}
ViewComponent + container
(帖子由prev screen传递。来自redux商店。)
import { FlatList } from 'react-native';
import { connect } from 'react-redux';
export class CommentList extends React.Component {
async componentWillMount() {
await this.props.dispatch(fetchComments(key)); <== to call redux action to fetch comments
}
renderItem = .... //skip the code
render() {
const { post, authorProfile } = this.props;
console.log("props post is ... ", post);
return (
<FlatList
style={styles.commentList}
renderItem={this.renderItem}
data={post.comments}
ListHeaderComponent={this.header(authorProfile)}
ListEmptyComponent={<Text>No Comments</Text>}
/>
);
}
}
CommentList.propType = {
post: PropTypes.object.isRequired,
};
function mapStateToPropsFactory(initialState, ownProps) {
const { createdBy } = ownProps.post;
return function mapStateToProps(state) {
return {
authorProfile: state.user.authorProfiles.find((profile) => (profile.uid === createdBy)),
};
};
}
export default connect(mapStateToPropsFactory)(CommentList);
动作
export const fetchComments = (postkey) => (dispatch) =>
new Promise(() => {
// fetching data ...
// and then receive comments
comments.forEach((comment) => {
dispatch({
type: 'ADD_COMMENT',
key: postkey,
comment
})
})
})
减速
case 'ADD_COMMENT':
return Object.assign([], state.map((data) => {
if (data.key === action.key) {
const oldComments = data.comments ? data.comments : [];
if (oldComments.map(m => m.key).includes(action.comment.key)) {
return data;
}
oldComments.push({
key: action.comment.key,
body: action.comment.body,
createdBy: action.comment.createdBy,
createdAt: action.comment.createdAt,
});
data.comments = Object.assign([], oldComments);
}
return Object.assign([], data);
}));
我正在使用Object.assign因为somebody-explain-to-me-why-we-never-write-directly-to-state-in-redux
我认为这没有错,但它没有正常工作。
当我第一次打开CommentList
时,不会显示评论。但是,当退回并重新打开时,它会显示出来。
所以,我认为这是因为redux无法检测到状态发生变化的对象。
我改变了这样的代码:
ViewComponent + container
function mapStateToPropsFactory(initialState, ownProps) {
const { key, createdBy } = ownProps.post; // add key
return function mapStateToProps(state) {
return {
authorProfile: state.user.authorProfiles.find((profile) => (profile.uid === createdBy)),
anyanyanyany: post: state.posts.allPost.find((post) => (post.key === key)), // add this statement
};
};
}
在我这样做之后,它正常工作。请告诉我如何在这种情况下编码reducer?