一、创建项目,安装依赖包
npm install create-react-app -g //安装创建react项目的脚手架
create-react-app 项目名称 //再利用脚手架 创建项目
或者不安装脚手架,直接创建项目:
npx create-react-app my-react-app(项目名称) //先将 my-react-app 下载到本地,用完删除
安装 redux
npm install redux --save
或
npm install --save redux react-redux
安装Ant design
npm install antd --save
二、Todos 案例
1、在src文件夹下创建store仓库,在仓库下创建index.js 和 reducer.js 文件如下图:

2、在 store/index.js 文件下,写如下代码:
/* 1. 引入创建仓库的函数 */
import { createStore } from 'redux'
/* 2. 引入 reducer */
import reducer from './reducer'
/* 3. 创建一个仓库 */
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() //配置Redux DevTools插件
)
/* 4. 导出整个仓库 */
export default store
3、在 store/reducer.js 文件下,写如下代码:
/* 单个 reducer */
/* 1、初始化数据 */
const defaultState = {
inputValue: 'write something',
list: [
'今天吃鸡腿饭',
'明天吃炒面筋',
'后天吃串串香'
]
}
/*
state 初始化状态值
action 这次操作类型和数据
*/
export default (state = defaultState, action) => {
// console.log(state, action);
if (action.type === 'changeInput') {
//Reducer里只能接收state,不能改变state
let newState = JSON.parse(JSON.stringify(state))
newState.inputValue = action.value
return newState
}
if (action.type === 'addItem') {
//Reducer里只能接受state,不能改变state
let newState = JSON.parse(JSON.stringify(state))
newState.list.push(newState.inputValue)
newState.inputValue = ''
return newState
}
if (action.type === 'deleItem') {
//Reducer里只能接受state,不能改变state
let newState = JSON.parse(JSON.stringify(state))
newState.list.splice(newState.inputValue, 1)
return newState
}
return state
}
4、在 src/App.js 文件下,写如下代码:
import React, { Component } from 'react'
/* 引入Ant design样式 */
import 'antd/dist/antd.css' // or 'antd/dist/antd.less'
import { Input, Button, List } from 'antd'
/* 1、引入 store */
import store from './store'
export default class App extends Component {
constructor(props){
super(props)
this.state= store.getState();
// this.changeInputValue = this.changeInputValue.bind(this)
store.subscribe(this.storeChange) //订阅模式
};
changeInputValue = (e) => {
// console.log(e.target.value)
const action = {
type: 'changeInput',
value: e.target.value
}
store.dispatch(action)
};
storeChange = ()=>{
this.setState(store.getState())
};
clickBtn = ()=>{
const action = {
type: 'addItem',
}
store.dispatch(action)
};
deleClick(index){
const action = {
type: 'deleItem',
index
}
store.dispatch(action)
}
render() {
return (
<div>
<div style={{margin: '15px'}}>
<Input autoFocus value={this.state.inputValue} style={ { width:'200px',marginRight:'5px' } } onChange={this.changeInputValue}/>
<Button type="primary" onClick={this.clickBtn}> 增加 </Button>
</div>
<div style={{margin:'15px', width:'250px'}}>
<List bordered dataSource={this.state.list} renderItem={(item,index) => (<List.Item onClick={this.deleClick.bind(this,index)}>{item}</List.Item>)}/>
</div>
</div>
)
};
};
博客介绍了React项目的创建及Todos案例实现。可选择不安装脚手架直接创建项目,还需安装redux和Ant design。在Todos案例中,需在src文件夹下创建store仓库及相关文件,并在各文件中编写对应代码。
1588

被折叠的 条评论
为什么被折叠?



