25.redux回顾,redux中的action函数异步 (2)

exp2:
数据交互

import React,{Component} from "react"; import {createStore,applyMiddleware} from "redux"; import thunk from "redux-thunk"; const url = "http://localhost:9000/api/v2/movie/in_theaters?city=北京"; //创建store //数据初始化 const initState = {subjects:[]}; //创建reducer const reducer = (state = initState,action = {})=>{ const {type} = action; switch(type){ case "GET": return {...state,subjects:action.payload}; default: return state; } } //创建store const store = createStore(reducer,applyMiddleware(thunk)); function fetchSyncAction(){ return function(dispatch){ fetch(url).then(res=>res.json()).then(data=>{ console.log(data.subjects); dispatch({type:"GET",payload:data.subjects}); }) } } //创建组件 class Fetch extends Component{ constructor(...args){ super(...args); store.subscribe(()=>{ console.log(store.getState()); this.forceUpdate(); }) } asyncFecth(){ store.dispatch(fetchSyncAction()); } fn(){ //url:"http://api.douban.com/v2/movie/in_theaters?city=北京", //url:"http://localhost:9000/api/v2/movie/in_theaters?city=北京", //store.dispatch(plusAsyncAction()); fetch(url).then(res=>res.json()).then(data=>{ console.log(data.subjects); store.dispatch({type:"GET",payload:data.subjects}); }) } render(){ return ( <div> { store.getState().subjects.map(({id,title})=>{ return <div key={id}>{title}</div>; }) } <input onClick={this.fn.bind(this)} value="普通fetch" type="button"/> <input onClick={this.asyncFecth.bind(this)} value="asyncFecth" type="button"/> </div> ); } } export default Fetch;

res:

image

dispatch(action) View -------------------> reducer ---------> newState 异步 同步 dispatch(asyncAction) dispatch(action) View ----------------------> middleware拦截 ---------------> reducer --------> newState 属性验证:

安装:cnpm i -D prop-types

参考:

Test.propTypes = { 属性:验证规则 optionalArray: PropTypes.array, optionalBool: PropTypes.bool, optionalFunc: PropTypes.func, optionalNumber: PropTypes.number, optionalObject: PropTypes.object, optionalString: PropTypes.string, optionalSymbol: PropTypes.symbol, }

exp1:

import React, { Component } from "react"; import PropTypes from "prop-types"; class Test extends Component { //判断name是否是字符串,若不是字符串则报错 //,isRequired表示空也判断 //写法二 static propTypes = { name: PropTypes.string.isRequired, } render() { const {name} = this.props; return ( <div>属性验证:name: {name}</div> ); } } //写法一 /*Test.propTypes = { name: PropTypes.string.isRequired, }*/ export default Test;

res:
符合判定不返回任何值,不符合则会报错,并提醒输入的是何种类型数据.

image

exp2:
自定义属性验证

import React, { Component } from "react"; // import PropTypes from "prop-types"; function Test(props){ return ( <div>属性验证:name: {props.name}</div> ); } const PropTypes = { string:function(props, propName, componentName){ if(typeof props[propName] !== "string"){ return new Error(`你输入的${propName}我期望的是 字符串 ,但是你给我的是 ${typeof props[propName]} `); } } } Test.propTypes = { name:PropTypes.string, } export default Test;

res:

image

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpzwfx.html