Redux配置文件

配置:

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(
    
    ,
    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(
    
        
    
    ,
    document.querySelector('#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 (
            

{this.props.a}

) } }
计数器完成

你可能感兴趣的:(Redux配置文件)