【react】---redux-actions的基本使用---【巷子】
<p> </p><p><span style="font-size: 18px"><strong>一、安装</strong></span></p>
<div class="cnblogs_code">
<pre>cnpm install --save redux-actions</pre>
</div>
<p> </p>
<p><span style="font-size: 18px"><strong>二、为什么使用 redux-actions</strong></span></p>
<p><span style="font-size: 14px">reducer使用switch case语句进行action类型判断,当action很多时候,reducer内容就不那么直观了。redux-actions简化了reducer和action的联系</span></p>
<p> </p>
<p><strong><span style="font-size: 18px">三、基本使用</span></strong></p>
<p><span style="font-size: 14px">1、创建action/actionCreator.js</span></p>
<div class="cnblogs_code">
<pre>import { createAction } from 'redux-actions'<span style="color: rgba(0, 0, 0, 1)">;
export const addnum </span>= createAction('ADDNUM')</pre>
</div>
<p>2、组件中引入使用</p>
<div class="cnblogs_code">
<pre>import React,{Component} from "react"<span style="color: rgba(0, 0, 0, 1)">;
import store from </span>"./store"<span style="color: rgba(255, 0, 0, 1)">
import {addnum} from "./action/actionCreator"</span></pre>
<div>
<div>export default class App extends Component{</div>
<div> constructor(){</div>
<div> super()</div>
<div> this.state = store.getState();</div>
<div> store.subscribe(this.handleUpdate.bind(this))</div>
<div> }</div>
<div> render(){</div>
<div> let {n} = this.state;</div>
<div> return (</div>
<div> <div></div>
<div> <h2>{n}</h2></div>
<div> <button onClick={this.handleClick.bind(this)}>点击</button></div>
<div> </div></div>
<div> )</div>
<div> }</div>
<div> handleClick(){</div>
<div> <span style="color: rgba(255, 0, 0, 1)">store.dispatch(addnum());</span></div>
<div> }</div>
<div> handleUpdate(){</div>
<div> this.setState(store.getState())</div>
<div> }</div>
<div>}</div>
</div>
</div>
<p>3、reducer中使用</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(255, 0, 0, 1)">import {handleActions} from 'redux-actions'</span><span style="color: rgba(0, 0, 0, 1)"><span style="color: rgba(255, 0, 0, 1)">;</span>
const defaultState </span>=<span style="color: rgba(0, 0, 0, 1)"> {
n:</span>10<span style="color: rgba(0, 0, 0, 1)">
}
export </span><span style="color: rgba(0, 0, 255, 1)">default</span><span style="color: rgba(0, 0, 0, 1)"> handleActions({
ADDNUM: (state, action) </span>=><span style="color: rgba(0, 0, 0, 1)"> {
let newState </span>=<span style="color: rgba(0, 0, 0, 1)"> {...state};
newState.n</span>++<span style="color: rgba(0, 0, 0, 1)">;
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> newState;
},
}, defaultState)</span></pre>
</div>
<p> </p><br><br>
来源:https://www.cnblogs.com/nanianqiming/p/11225428.html
頁:
[1]