Redux狀態管理6Redux除錯工具
阿新 • • 發佈:2019-01-29
使用 react-redux
- 老趙 雖然能力 很強,但是用起來比較麻煩 ,為了方便管理,使用魏和尚來 負責 連結
- cnpm i –save react-redux
- 忘記 subscribe ,記住 reducer action dispatch
- React-redux 提供了 2個介面 ,Provider , connect 提供 連結的 功能
react-redux 的具體使用
- Provider 元件應該在最外層,傳入store 即可,只用一次.
- connect 負責從外部獲取元件需要的引數
- Connect 可以用裝飾起的方式來寫
Index.js
import React from "react"
import ReactDom from "react-dom"
import { createStore , applyMiddleware ,compose } from "redux"
import thunk from "redux-thunk"
import { Provider } from "react-redux"
import App from "./App"
import { counter} from "./index.redux"
const store = createStore(counter,
compose(applyMiddleware(thunk),
window .devToolsExtension?window.devToolsExtension():f=>f))
ReactDom.render(
(<Provider store = {store}>
<App />
</Provider>),
document.getElementById("root")
)
App.js
import React from "react"
import { Button } from "antd-mobile"
import {connect} from "react-redux"
import {addGun,ReduceGun,FakerGun,addGunAsync} from "./index.redux"
class App extends React.Component{
// constructor(props){
// super(props);
// }
render(){
return(
<div>
<Button type="primary" >現在有機槍{this.props.num}把</Button>
<Button type="primary" onClick={this.props.addGun}>申請武器</Button>
<Button type="primary" onClick={this.props.ReduceGun}>收繳武器</Button>
<Button type="primary" onClick={this.props.FakerGun}>搶武器</Button>
<Button type="primary" onClick={ this.props.addGunAsync }>拖2秒</Button>
</div>
)
}
}
const mapStatetoProps = (state)=>{
return {num:state}
}
const actionCreaters = {addGun,ReduceGun,FakerGun,addGunAsync}
App = connect(mapStatetoProps,actionCreaters)(App)
export default App
Index.redux.js
const ADD_GUN = "加機關槍"
const REMOVE_GUN = "減機關槍"
const FAKE_GUN = "搶機關槍"
/*reducer*/
export function counter (state=0,action){
switch(action.type){
case ADD_GUN:
return state + 1
case REMOVE_GUN:
return state - 1
case FAKE_GUN:
return state * 10
default:
return 10
}
}
export function addGun(){
return {type:ADD_GUN}
}
export function ReduceGun(){
return {type:REMOVE_GUN}
}
export function FakerGun(){
return {type:FAKE_GUN}
}
export function addGunAsync(){
return dispatch=>{
setTimeout(()=>{dispatch(addGun())},500)
}
}