我有一个包含三个孩子的父反应组件:
<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}))
}
答案 0 :(得分:2)
每次安装TweetColumn
时,您都在进行api调用。如果您有多个TweetColumn
组件,并且每个组件都进行api调用,则最后一个到达的响应都将设置state.tweets.items
的值。这是因为您每次都调度相同的操作FETCH_TWEETS_SUCCESS
(最后一个优先于前一个)。为了解决该问题,假设响应中有一个category
(foo,bar,baz),我将通过以下方式编写reducer:
export default function tweetReducer(state = initialState, action) {
switch (action.type) {
case FETCH_TWEETS_SUCCESS:
return {
...state,
[action.data.category]: action.data
}
default:
return state;
}
}
然后,您可以在TweetColumn
组件中执行以下操作:
class TweetColumn extends Component {
componentDidMount() {
this.props.fetchTweets(this.props.column)
}
render() {
const { column } = this.props;
const tweetItems = this.props.tweets[column].map(tweet => (
<div key={ tweet.id }>
{ tweet.name }
</div>
)
return (
<div className="box-content">
{ tweetItems }
</div>
)
}
}
const mapStateToProps = state => ({
tweets: state.tweets
})
const mapDispatchToProps = dispatch => ({
fetchTweets: column => dispatch(fetchTweets(column))
})
export default connect(
mapStateToProps,
mapDispatchToProps,
)( TweetColumn )
您必须进行一些验证,以确保tweets[column]
存在,但是您明白了。