redux 学习笔记

来源:互联网 发布:java简历 编辑:程序博客网 时间:2024/05/24 03:28

redux的基本原则:

Flux的基本原则是“单项数据流”,redux的基本原则强调三个基本原则:

1.唯一数据源(single source of truth);

应用的状态只存储在唯一的store上。

2.保持状态只读(state is read-only);

不能直接去修改状态,如果要修改状态,必须通过派发的一个action对象完成,这一点和flux类似。

3.数据改变只能通过纯函数完成(changes are made with pure functions);

纯函数:reducer(state,action) 相同的输入对应相同的输出。


将一个react组件分成:容器组件和傻瓜组件:

容器组件:处于外层,和redux store打交道,读取store的状态,用于初始化组件的状态,同时还要监听store的状态的改变;当store状态改变的时候,需要更新组件,从而驱动组件从新渲染,当需要更新store时,就要派发action对象。

class CouterContainer extends Component{

render(){

return <Counter caption={this.props.caption}

onIncrement = {this.onIncrement}

onDecrement = {this.onDecrement}

}

}

傻瓜组件:处于内层,根据当前的props和state,渲染出用户的界面。

class Counter extends Component{

render(){

const {caption, onIncrement, onDecrement, value} = this.props;

return(

<div>

<button style={buttonstyle} onclick={onIncrement}>+</button>

<button style={buttonstyle} onclick={onDecrement}>-</button>

   </div>

)

}

}

容器组件和傻瓜组件之间的通信使用props属性。



组件context:

context顾名思义就是上下文的意思,表示承接store和下面的组件,让一个树状组件上所有的组件都能访问的一个共同的对象。

首先,上级组件宣称自己支持context,并提供一个函数来返回代表context的对象,然后,这个上级组件之下的所有的子组件,只要宣称自己需要这个context,就可以通过this.context来访问这个共同的环境对象了。

用特殊的react组件Provider 代替context功能:

import {PropType,Component} from 'react';

class Provider extends Component{

getChildContext(){

return {

store:this.props.store;

};

}

render(){

return this.props.children;

}

}

props中有一个特殊的children,代表子组件。

除了把渲染的工作交给子组件,Provider还要提供一个函数getChildContext,这个函数返回的是代表Context的对象。

为了让Provider被react认可,还需要指定Provider的childContextType的属性。

Provider.childContextType = {

store:PropTypes.object;

}


同理,为了让子组件可以访问Context,需要在子组件中ContextType赋值,不然就无法访问,加入子组件是ConterContainer:

ConterContainer.contextType = {

store:PropType.object;

}




原创粉丝点击