Redux配置文件

2019-08-15  本文已影响0人  smartfeng

配置:

redux 是可预测状态容器,react-redux 是让 reactredux 结合工作的粘合剂,创建 reducers文件夹 ,创建计数器的文件,counterReducer.js 文件,这个文件向外默认暴露一个 reducer

export default (state = {'a': 10}, action) => {
    if(action.type === 'ADD'){
        return {
            ...state,
            'a': state.a + 1
        }
    }else if(action.type === 'PF'){
        return {
            ...state,
            'a': state.a * state.a
        }
    }
    return state;
}

更改入口文件 main.js 。引入 createStore 函数、引入刚刚创建的 reducer文件 ,创建 store ,弹出a

弹出a
import React from 'react';
import ReactDOM from 'react-dom';
import {createStore} from 'redux';
import counterReducer from './reducers/counterReducer.js';
import App from './App.js';
const store = createStore(counterReducer);
//弹出a
alert(store.getState().a);
ReactDOM.render(
    <App />
    ,
    document.querySelector('#app')
);

引入Provider组件,注意它是一个组件,大写P!!!从react-redux中引入!!

import React from 'react';
import ReactDOM from 'react-dom';
import {createStore} from 'redux';
//引入Provider
import {Provider} from 'react-redux';
import counterReducer from './reducers/counterReducer.js';
import App from './App.js';
const store = createStore(counterReducer);

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>
    ,
    document.querySelector('#app')
);

<Provider> 要包裹<App />组件,属性是store={store}
进入App.js文件

import React, { Component } from 'react';
import {connect} from 'react-redux';
//装饰器
@connect(
    (state) => ({
        a: state.a
    }),
    (dispatch) => ({
        dispatch
    })
)
export default class App extends Component {
    render() {
        return (
            <div>
                <h1>{this.props.a}</h1>
                <button onClick={()=>{
                    this.props.dispatch({"type": "ADD"});
                }}>按我加1</button>

                <button onClick={()=>{
                    this.props.dispatch({"type": "PF"});
                }}>按我平方</button>
            </div>
        )
    }
}
计数器完成
上一篇下一篇

猜你喜欢

热点阅读