redux基础使用-redux flow

结合一个todoList我们学习一下redux的原理和基本使用,先看一张图

结合这张图方便我们的理解。首先store就相当于一个管理员,reducer就相当于我们的数据库,用来记录数据的进出。action是用来操作的指令,去更新reducer中的数据。下面结合代码我们看一下。代码结构如下

                                                 

在核心文件store中index.js中 创建reducer 也就是我们最终要操作的数据库

import { createStore } from 'redux';
import reducer from './reducer';

const store = createStore(reducer);

export default store;

reducer.js代码如下

const defaultState = {
	inputValue: '123',
	list: [1, 2]
}

export default (state = defaultState, action) => {
	return state;
}

然后在使用的地方。我们引入store并获取数据

import React, { Component } from 'react';
import 'antd/dist/antd.css';
import { Input, Button, List } from 'antd';
import store from './store';
	constructor(props) {
		super(props);
		this.state = store.getState();
	}
	
render() {
		return (
			<div style={
   
   {marginTop: '10px', marginLeft: '10px'}}>
				<div>
					<Input value={this.state.inputValue} placeholder='todo info' style={
   
   {width: '300px', marginRight: '10px'}}/>
					<Button type="primary">提交</Button>
				</div>
				<List
					style={
   
   {marginTop: '10px', width: '300px'}}
		      bordered
		      dataSource={this.state.list}
		      renderItem={item => (<List.Item>{item}</List.Item>)}
		    />
			</div>
		)

猜你喜欢

转载自blog.csdn.net/lee727n/article/details/108850514
今日推荐