【发布时间】:2015-12-26 10:26:18
【问题描述】:
在下面的代码中,如果我只从mapStateToProps 返回一个topic 对象,则SingleTopic 组件在状态更新时不会重新渲染。但是如果我从它返回{ topic, state },组件就会重新渲染。
import React from 'react';
import { connect } from 'react-redux';
import SingleTopic from '../components/SingleTopic';
import { incrementTopicRating, decrementTopicRating } from '../actions/forum';
let mapStateToProps = (state, ownProps) => {
let topic = state.filter((t) => {
return +t.id === +ownProps.params.id;
})[0];
return { topic };
};
let mapDispatchToProps = (dispatch) => {
return {
onUpvote: (id) => { dispatch(incrementTopicRating(id)); },
onDownvote: (id) => { dispatch(decrementTopicRating(id)); }
};
};
export default connect(mapStateToProps, mapDispatchToProps)(SingleTopic);
我可能做错了什么,但据我了解,传递给connect 的组件应该会在状态更新时自动更新。谁能解释一下我的错误在哪里?
减速机:
export default (state = [], action) => {
switch (action.type) {
case 'ADD_TOPIC': return addTopic(state, action);
case 'INCREMENT_TOPIC_RATING': return incrementTopicRating(state, action);
case 'DECREMENT_TOPIC_RATING': return decrementTopicRating(state, action);
default: return state;
}
};
const addTopic = (state, action) => {
let { title, body, id, rating } = action;
let newTopic = { title, body, id, rating };
return [newTopic, ...state];
};
const incrementTopicRating = (state, action) => {
return state.map((topic) => {
if (+topic.id === +action.id) {
topic.rating += 1;
return topic;
}
return topic;
});
};
const decrementTopicRating = (state, action) => {
return state.map((topic) => {
if (+topic.id === +action.id) {
topic.rating -= 1;
return topic;
}
return topic;
});
};
UPD
如果我向返回的对象添加第二个属性,则会呈现 SingleTopic 组件。而且这个属性必须是数组或者对象类型,像这样:
let foo = [];
return { topic, foo };
【问题讨论】:
-
问题可能出在你的减速器上。你能显示那个代码吗?
-
添加了减速器。问题是状态变化很好,
mapStateToProps被调用,但组件没有被渲染。