最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

DAY25:flux想解決什麼問題?

XAMPP下载 admin 934浏览 0评论
 flux是一個模式而不是一個框架,所以使用flux並不會有太多新的程式碼,所以我們主要了解這個模式概念是什麼,flux到底想解決什麼問題?

react以撰寫components可重覆利用組合而成新頁面,但所有資料都是包在元件之中,元件只能透過setState來改變state狀態,元件相互溝通時只能靠著props去進行傳遞,如果多個元件互相傳遞或層級傳遞變得極為複雜,更新資料又是層層更新,flux設計模式就是為了解決這樣子的問題。

component只能透過setState改變state,但我們能透過傳遞方法到child元件來改變parent元件的state,這就是我想表達的層層傳遞,層層更新會變得很混雜。

src/Parent.js

import React, { Component } from ‘react’;
import Child from ‘./Child’;

class Parent extends React.Component {
constructor(props) {
super(props);
this.handleFn = this.handleFn.bind(this);
this.state = {parentval: “parent”};
}

handleFn(param) {
this.setState({parentval: param});
};

render() {
return (
<div>
<h1>{this.state.parentval}</h1>
<Child fn={this.handleFn}/>
</div>
);
}
}

export default Parent;
src/Child.js

import React, { Component } from ‘react’;

class Child extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {parentval: “parent”};
}

handleClick() {
this.props.fn(‘Change-Parent-State’);
}

render() {
return <h1 onClick={this.handleClick}>child</h1>;
}
}

export default Child;
Flux Parts

Dispatcher
Store
Action
View
Flux官網示意圖(單向資料流)

QQ截图20180917132420
 Dispatcher
主要用途接收action(actionType & payload資料),再發送給所有註冊的callback。這在設計模式類似於發佈/訂閱模式(Publish/Subscribe Pattern),而每一個應用程式只會有一個singleton dispatcher,再由這一個dispatcher統一發送。

Store
每個store都在dispatcher上註冊,提供一個callback方法,每當有action產生時相對應的callback會被呼叫使用。

Action
定義內部API,當方法觸發時發送給dispatcher,基本的flux action:

{
type: ‘ADD_TODO’,
payload: {
text: ‘Do something.’
}
}
View
從store接收資料將資料(props)傳遞到子元件並render

转载请注明:XAMPP中文组官网 » DAY25:flux想解決什麼問題?

您必须 登录 才能发表评论!