react+redux的一些经验

一个注意点是store绑定后在子件获取不到值。

要在子件增加

 

header.contextTypes = { store: PropType.object.isRequired }

 

index.js

 

import React,{Component} from 'react';
import PropType from 'prop-types';
import ReactDOM from 'react-dom';
import {createStore} from 'redux';
import {Provider, connect} from 'react-redux';
import {increaseAction} from './redux/action';
import {counter} from './redux/reducer';
import Header from './components/header';
import './index.less';
import './assets/css/base.less';


class Counter extends Component{
    constructor(props){
        super(props);
        this.initFontSise();
    }

    initFontSise(){
        var docEl = document.documentElement
        var clientWidth = docEl.clientWidth
        if (!clientWidth) return
        docEl.style.fontSize = 20 * (clientWidth / 320) + 'px'
        // 判断是否在安卓和ios运行
        var u = navigator.userAgent
        if (!(u.indexOf('Android') > -1 || u.indexOf('Adr') > -1)) {
            if (!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
                docEl.style.fontSize = 40 + 'px'
            }
        }
    }

    render(){
        const {valueText, onIncreaseClick} = this.props;
        return(
            
{valueText}
) } } //定义类型 Counter.propTypes = { valueText: PropType.number.isRequired, onIncreaseClick: PropType.func.isRequired } //Store const store = createStore(counter); //映射state到组件的props function mapStateToProps(state){ return{ valueText:state.count } } //映射actions到组件的props function mapDispatchToProps(dispatch){ return{ onIncreaseClick: () => dispatch(increaseAction) } } //把state和action塞到redux容器 const App = connect( mapStateToProps, mapDispatchToProps )(Counter); ReactDOM.render( , document.getElementById('root') )

2.header.js

 

 

import React,{Component} from 'react';
import PropType from 'prop-types';
import '../components/header.less';

class header extends Component{
    constructor(props, context){
        super(props,context);
        console.log(props);
        console.log(context.store.dispatch);
    }

    render() {
        const {onIncreaseClick} = this.context.store;
        return (
            
        );
    }
}

header.contextTypes = { store: PropType.object.isRequired }

export default header;

3.action

 

 

//Action
export const increaseAction = {type: 'increase'}

4.reducer.js

 

 

//Reducer
export function counter(state = {count: 0}, action){
    const count = state.count
    switch (action.type){
        case 'increase':
            return {count:count + 1}
        default:
            return state
    }
}

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(React点滴知识)