本节知识点
(1) 简介Redux作用
(2) 使用Redux
(一) Redux介绍
Redux 就是相当于Vue中的 Vuex 存放公共数据的地方。比如兄弟之间传值等等
(二) 使用Redux
- (1) 安装
npm i redux -S
- (2) 在src目录下创建一个store文件夹,里面创建一个index.js文件作为公共仓库
import { createStore } from 'redux'
//引入reducer
import reducer from './reducer'
//放入reducer
const store = createStore(reducer)
export default store
- (3) 创建reducer文件,他里面接收两个参数 state,action antion下篇在讲,state就是获取到所有的公共数据
const defaultState = {
inputValue: '123',
list: [
'Racing car sprays burning fuel into crowd.',
'Japanese princess to wed commoner.',
'Australian walks 100km after outback crash.',
'Man charged over missing wedding girl.',
'Los Angeles battles huge wildfires.'
]
}
export default (state = defaultState, action) => {
return state
}
- (4) 组件里面引入
import React, { Component } from 'react'
import { Input, Button, List } from 'antd'
import 'antd/dist/antd.css'
//引入仓库文件
import store from './store/index'
class App extends Component {
constructor(props) {
super(props)
// 获取仓库数据的话就是store.getState();
console.log(store.getState())
//输出的结果就是indexValue,list
this.state = store.getState()
}
render() {
return (
<div>
<Input
placeholder="Basic usage"
value={this.state.inputValue}
onChange={this.cahngevalue.bind(this)}
style={{ width: '300px', marginRight: '20px' }}
/>
<Button type="primary" onClick={this.change.bind(this)}>
提交
</Button>
<List
style={{ width: '300px', marginTop: '20px' }}
header={<div>Header</div>}
footer={<div>Footer</div>}
bordered
dataSource={this.state.list}
renderItem={item => <List.Item>{item}</List.Item>}
/>
</div>
)
}
change(e) {
console.log(e.target)
}
cahngevalue(e) {
let value = e.target.value
this.setState({
value
})
}
}
export default App