Redux 入门
安装
使用之前了解 Redux 的一些核心概念:
使用引入import { createStore } from 'redux'; // 或 const { createStore } = require('redux'); 定义一些 action creators:function increment() { return { type: 'INCREMENT' }; } function decrement() { return { type: 'DECREMENT' }; } 定义一个 reducer,用来根据 action 的 type 生成新的 store:function counter(state = 0,action) { switch(action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default : return state; } } 根据上面定义的 reducer 创建 store:const store = createStore(counter); 模拟 action:let currentValue = store.getState(); const listener = () => { const previousValue = currentValue; currentValue = store.getState(); console.log(` 之前的值:${previousValue},现在的值:${currentValue}`); }; // 订阅监听函数,动作分发后回调 store.subscribe(listener); // 分发动作 store.dispatch(increment()); store.dispatch(increment()); store.dispatch(decrement()); 结果:
使用 react-redux 与 React 集成安装
使用之前先定义一些 React 组件: // Counter.js import React from 'react'; import { connect } from 'react-redux'; import * as ActionCreators from './ActionCreators'; function Counter({value,increment,decrement}) { return ( <p> Click: {value} times {' '} <button onClick={increment} >+</button>{' '} <button onClick={decrement} >-</button>{' '} </p> ); } export default connect( state => ({ value: state}),ActionCreators )(Counter); 在 // ActionCreators.js export function increment() { return { type: 'INCREMENT' }; } export function decrement() { return { type: 'DECREMENT' }; } 使用 react-redux// App.js import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import Counter from './Counter'; // ... 省略上面已经定义好的 reducer 和 store ReactDOM.render( <Provider store={store}> <Counter /> </Provider>,document.getElementById('root') ); 可以看到,我们使用了一个 react-redux 提供的 结果
用后思考当然,这个例子非常简单,根本不需要用到 redux,因为这个例子只有一个组件。如果你有过使用 // App.js // ... ReactDOM.render( <Provider store={store}> <SomeComponent /> </Provider>,document.getElementById('root') ); function SomeComponent(props) { return ( <div> <h1>SomeComponent</h1> <OtherComponent /> </div> ); } function OtherComponent(props) { return ( <div> <h2>OtherComponent</h2> <Counter /> </div> ); } 上述组件应该在各自独立的文件中定义,为了节省篇幅,因此我把它们都写在 结果
可以看到,我们嵌套了两层组件,但是 Counter 组件不需要层层嵌套来获取祖先级组件的 state,我们只需要将所有的 state 提取到 我们学到了什么?通过使用 redux 和 react-redux 来集中管理 state,以更加优雅的方式传递父级容器组件的 state。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |