Redux学习笔记:Redux简易开发步骤

该文章不介绍Redux基础,也不解释各种乱乱的概念,网上一搜一大堆。只讲使用Redux开发一个功能的步骤,希望可以类我的小白们,拜托它众多概念的毒害,大牛请绕道!

本文实例源代码参考:React-Redux-Primary-Demo 中的webapp/redux/index.js、webapp/redux/reducers/index.js、webapp/redux/components/Counter.js(为了讲解方面,本文示例代码所有改动,但大致相同)。

演示地址:Redux实例演示

1.创建主文件js,比如index.js

2.定义render入口并调用Counter

const render = () => ReactDOM.render(
    <Counter showtxt={} clickHandle={}/>,$('#wrapper')[0]
)

3.定义Counter,也就是React Component,生成DOM结构,render时触发。

class Counter extends Component {
    render() {
        return <div onClick={this.props.clickHandle}>我是Counter的div。{this.props.showtxt}</div>
    }
}
export default Counter

4.初始化显示,手动调用render(),第一次初始化时定义,后续不在执行。

render();

至此,就可以吧Counter内容显示到页面上了。接下来我们就来实现clickHandle事件。
重要说明:Redux是通过改变状态state来改变视图view的(他们是一一对应的),但是我们不能像React那样setState,只能通过Reducer生成新的state,而Reducer执行是通过store.dispatch调用的。
基于这一点,我们继续。。。

5.创建store,并绑定reducer

const store = createStore(reducer); // createStore的第一个参数必须是个函数,store.dispatch()时执行,该函数就叫reducer

6.定义Action,调用store.dispatch

<Counter showtxt={store.getState().showtxt} clickHandle={() => {store.dispatch({ type: 'clickdiv' })}}/>,$('#wrapper')[0]) // 修改步骤2的代码

7.定义Reducer,生成新的state

function counter(state = {count: 0,showtxt: ''}, action) {
    const count = state.count
    switch (action.type) {
        case 'clickdiv':
            return {
                count: count + 1,
                showtxt: '你不小心点到了我' + (count + 1) + '次'
            }
        default:
            return state
    }
}

说明:这里只修改要state中变化的值,如果state是对象,return的时候需要把其他值带上。

到这里,貌似已经完整了,点击只执行store.dispatch、调用Reducer生成新的state,state又和view绑定自动更新,应该可以了吧?
实际不可以,因为,上面只是生成了新额state,要想跟view绑定,还有最后一步:监听state变化执行render。

8. 定义state变化监听

store.subscribe(render)

至此,redux基本调用流程彻底完成。流程总结如下:

原文地址:https://www.cnblogs.com/yinluhui0229/p/6709782.html