react -redux 存取数据简单使用

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);
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值