Redux学习之旅二:创建Redux仓库store和reducer

首先要安装Redux,打开终端输入以下命令:

npm install --save redux

一、编写创建store仓库

store是Redux工作流程中非常重要的一部分,它负责所有数据的管理。

首先在src目录下新建一个store文件夹,并在store下新建index.js文件。index.js就是整个项目的store文件,该文件代码内容如下:

import {createStore} from 'redux';//引入createStore方法
const store = createStore();  //创建数据存储仓库
export default store;

在store下新建文件reducers.js,内容如下:

const defaultState = {} //默认数据
export default (state = defaultState,action)=>{
    return state
}

在store中引入reducer,再创建store:

import {createStore} from 'redux';
import reducer from './reducer';
const store = createStore(reducer)  //reducer注入
export default store;

二、在store中初始化TodoList数据

在reducers.js文件的defaultState中添加inputValue和list属性:

const defaultState = {
    inputValue : 'Write Something',
    list: [
        '早8点开晨会,分配今天的代码任务',
        '早9点和项目经理开需求沟通会',
        '早10点学习技术知识'
    ]
}
export default (state = defaultState,action)=>{
    return state
}

三、组件获取store数据

引入store:

import store from './store'; //表示'./store/index.js'

TodoList.js文件:

import React, { Component } from 'react';
import 'antd/dist/antd.css';
import { Input , Button ,List} from 'antd';
import store from './store'; //表示'./store/index.js'

class TodoList extends Component {
    constructor(props){
        super(props);
        console.log(store.getState());
        this.state = store.getState();
    }
    
    render() { 
        return ( 
            <div style={{margin:'10px'}}>
                <div>
                    <Input 
                        placeholder={this.state.inputValue} 
                        style={{width:'250px', marginRight:'10px'}}
                    />
                    <Button type="primary">增加</Button>
                </div>
                <div style={{margin:'10px',width:'300px'}}>
                    <List
                        bordered
                        dataSource={this.state.list}
                        renderItem={item=>(<List.Item>{item}</List.Item>)}
                    />
                </div>
            </div>
         );
    }
}
 
export default TodoList;

运行结果:

store数据获取成功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值