react redux 使用
详情可查看github dome 演示文件 https://github.com/fuyunchun/react-redux-demo.git
index.js 入口文件
import React from 'react';import ReactDOM from 'react-dom';
import App from './app'
import {Provider} from 'react-redux'
import {createStore,applyMiddleware} from 'redux'
import {BrowserRouter} from 'react-router-dom'
import thunk from 'redux-thunk'; //处理异步的中间件,(和applyMiddleware一起使用)
import reducer from './reducer'
const store = createStore(reducer,applyMiddleware(thunk))
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
,document.getElementById('root')
);
app.js自定义组件
import React from 'react'import {Link , Route} from 'react-router-dom'
import {connect} from 'react-redux'
import {ADD,REMOVE,ASYNC} from './counder'
function kehuan(){
return <h1>《科幻类图书》</h1>
}
function xiaoshui(){
return <h1>《小说类图书》</h1>
}
// 使用 @connect 需要安装redux装饰器,详情见下
https://www.cnblogs.com/tlfe/p/13930332.html
@connect(
// state => ({num:state}), 没有合并reducer之前这么用
state => ({num:state.counder}),
{ADD,REMOVE,ASYNC}
)
class App extends React.Component{
render(){
return (
<div>
<ul>
<li>
<Link to="/">科幻类图书</Link>
</li>
<li>
<Link to="/xiaoshui">小说类图书</Link>
</li>
</ul>
<Route path="/" exact component={kehuan}></Route>
<Route path="/xiaoshui" component={xiaoshui}></Route>
<div>还剩{this.props.num}本图书</div>
<button onClick={this.props.ADD.bind(this)}>申请图书</button>
<button onClick={this.props.REMOVE.bind(this)}>上交图书</button>
<button onClick={this.props.ASYNC}>缓两天在交</button>
</div>
)
}
}
export default App
counder.js 文件
const add = '申请图书'const remove = '上交图书'
function counder(state=0,action){
switch(action.type){
case add : return state + 1
case remove : return state - 1
default : return 10
}
}
function ADD(){
return {type:add}
}
function REMOVE(){
return {type:remove}
}
// 处理异步的
function ASYNC(){
return dispatch => {
setTimeout(() => {
dispatch(REMOVE())
},2000)
}
}
export {
counder,
ADD,
REMOVE,
ASYNC
}
reducer.js 合并多个reducer
// 合并多个 reducerimport {combineReducers} from 'redux'
import {counder} from './counder'
// 有多少个直接在下面加
export default combineReducers({
counder
})
以上是 react redux 使用 的全部内容, 来源链接: utcz.com/z/384000.html