1.首先,在自定义的组件中新建store文件夹,并在store下新建reducer.js文件,编写代码:
import {fromJS} from 'immutable';
const defaultState = fromJS({
topicList:[{
"id":1,
"text":"社会热点",
"url":"https://upload.jianshu.io/collections/images/14/6249340_194140034135_2.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/64/h/64"
},{
"id":2,
"text":"社会热点",
"url":"https://upload.jianshu.io/collections/images/14/6249340_194140034135_2.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/64/h/64"
},{
"id":3,
"text":"社会热点",
"url":"https://upload.jianshu.io/collections/images/14/6249340_194140034135_2.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/64/h/64"
},]
});
export default (state = defaultState,action) => {
switch (action.type) {
default:
return state;
}
}
2.在最大的reducer中引用该小reducer,存储数据:
import {combineReducers} from 'redux-immutable';/*可以将小的reducer 合并成 大的reducer*/
import homeReducer from '../pages/home/store/reducer';
const reducer = combineReducers({
home:homeReducer
});
export default reducer;
3.在自定义组件中取数据
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {TopicWrapper,TopicItem} from '../style';
class Topic extends Component{
render() {
return(
<TopicWrapper>
{
this.props.list.map((item)=>{
return (
<TopicItem key={item.get("id")}>
<img className='topic-pic' src={item.get("url")} alt=""/>
{item.get("text")}
</TopicItem>
)
})
}
</TopicWrapper>
)
}
}
const mapState = (state) => ({
list: state.get("home").get("topicList")
});
export default connect(mapState,null)(Topic);