react基礎筆記 model分層

2021-10-11 09:27:34 字數 3807 閱讀 6670

};1.1.1.獲取model中的資料

接下來,建立model檔案,在umi中,約定在src/models資料夾中定義model,所以,在該資料夾下建立listdata.js檔案:

export

default

}

import react from

'react'

;import

from

'dva'

;const namespace =

'list'

;const

mapstatetoprops

=(state)

=>;}

;//定義乙個函式,將model中的資料繫結到this.props中,將函式傳入註解中

@connect

(mapstatetoprops)

class

list

extends

react.component

>

<

/li>})

}<

/ul>

onclick=);}

}>

新增<

/button>

<

/div>);

}}export

default list;

測試:

繫結資料到this.props中

流程說明:

umi框架啟動,會自動讀取models目錄下model檔案,即listdata.js中的資料

@connect修飾符的第乙個引數,接收乙個方法,該方法必須返回{},將接收到

model資料

在全域性的資料中,會有很多,所以需要通過namespace進行區分,所以通過

state[namespace]進行獲取資料

拿到model資料中的data,也就是[1, 2, 3]資料,進行包裹{}後返回

返回的資料,將被封裝到this.props中,所以通過this.props.listdata即可獲取到

model中的資料

1.1.2.修改model中的資料

export

default

, reducers:}}

}

import react from

'react'

;import

from

'dva'

;const namespace =

'list'

;const

mapstatetoprops

=(state)

=>;}

;const

mapdispatchtoprops

=(dispatch)

=>);

}}}@connect

(mapstatetoprops, mapdispatchtoprops)

//mapdispatchtoprops:函式,將方法對映到props中

class

list

extends

react.component

>

<

/li>})

}<

/ul>

//此時可直接呼叫this.props中的addnewdata方法

onclick=

>

新增<

/button>

<

/div>);

}}export

default list;

1.1.3.在model中請求資料
// import fetch from 'dva/fetch';

function

checkstatus

(response)

const error =

newerror

(response.statustext)

; error.response = response;

throw error;

}/**

* requests a url, returning a promise.

* * @param url the url we want to request

* @param [options] the options we want to pass to "fetch"

* @return an object containing either "data" or "err"

*/export

default

async

function

request

(url, options)

import request from

'../util/request'

;export

default

, reducers:

let maxnum = state.maxnum +1;

let list =

[...state.data, maxnum]

;return}}

, effects:

= sagaeffects;

//獲取到call、put方法

const url =

"/ds/list"

;// 定義請求的url

let data =

yield

call

(request, url)

;//執行請求,並接受返回值

yield

put();}}}

import react from

'react'

import

from

'dva'

;const namespace =

"list"

;@connect

((state)

=>},

(dispatch)

=>)}

,//將初始化方法對映到props中

init:()

=>)}

}})class

list

extends

react.component;}

//元件載入完後進行初始化操作

componentdidmount()

render()

>

<

/li>})

}<

/ul>

onclick=

>

新增<

/button>

<

/div>);

}}export

default list;

1.1.4.mock模擬請求資料

在專案根目錄下建立mock目錄,然後建立mocklistdata.js檔案,並且輸入如下內容:

export

default);

}}

當請求此路徑時便可響應數

react封裝函式 React 基礎學習筆記

內容 intro install page setup react elements reactdom react component react factories names abstract react.createelement reactdom.render react.component...

React學習筆記 Redux基礎篇

redux,狀態管理器,將state進行統一的管理,適用於複雜的使用者操作 需要協同的使用者操作 涉及到許可權的網頁 多資料來源等場景。action 顧名思義,動作。需要執行怎樣的操作,action是乙個物件,內部包含了此action的型別和相關資訊,規範的action如下 每次都寫一遍action...

ruby on rails 測試筆記(model)

第一種 require spec helper.rb describe test do describe make test for do let course let user let before it 建立乙個新試卷並隨機選出10道題組卷 do user.should eq user cour...