【发布时间】:2018-12-04 17:59:12
【问题描述】:
我有一个包含 3 个孩子的父反应组件:
<ChildComponent category="foo" />
<ChildComponent category="bar" />
<ChildComponent category="baz" />
子组件根据prop类别值调用api:
http://example.com/listings.json?category=foo
在我的操作中,数据按预期返回。但是,当子组件呈现数据时。最后一个子 baz 也覆盖了它在 foo 和 bar 中的值。
solution to this problem seems to be given here。但我希望这是动态的,并且仅取决于类别道具。这在 Redux 中是不可能的吗?
我的子组件如下所示:
class TweetColumn extends Component {
componentDidMount() {
this.props.fetchTweets(this.props.column)
}
render() {
const { tweets, column } = this.props
if (tweets.length === 0) { return null }
const tweetItems = tweets[column].map(tweet => (
<div key={ tweet.id }>
{ tweetItems.name }
</div>
)
return (
<div className="box-content">
{ tweetItems }
</div>
)
}
}
TweetColumn.propTypes = {
fetchTweets: PropTypes.func.isRequired,
tweets: PropTypes.array.isRequired
}
const mapStateToProps = state => ({
tweets: state.tweets.items
})
export default connect(mapStateToProps, { fetchTweets })( TweetColumn )
减速器:
export default function tweetReducer(state = initialState, action) {
switch (action.type) {
case FETCH_TWEETS_SUCCESS:
return {
...state,
[action.data[0].user.screen_name]: action.data
}
default:
return state;
}
}
export default combineReducers({
tweets: tweetReducer,
})
行动:
export const fetchTweets = (column) => dispatch => {
dispatch({ type: FETCH_TWEETS_START })
const url = `${ TWITTER_API }/statuses/user_timeline.json?count=30&screen_name=${ column }`
return axios.get(url)
.then(response => dispatch({
type: FETCH_TWEETS_SUCCESS,
data: response.data
}))
.then(response => console.log(response.data))
.catch(e => dispatch({type: FETCH_TWEETS_FAIL}))
}
【问题讨论】:
-
使用
key道具?? -
@xadm 只需将 key prop 传递给子组件?那没用。
-
keys 应该用于所有相同类型的孩子以帮助区分它们... case .. redux ...您可能正在寻找reselect
-
你能告诉我们你是如何在你的 redux reducer 中更新
tweets的吗?我猜你在成功的 api 响应产生的每一个动作上都会覆盖它。 -
@nebuler 更新了问题
标签: reactjs redux react-redux