React 通过axios调用服务接口渲染无状态组件详解

一、axios

概念:Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。(个人理解就是ajax,用来请求和响应数据)

安装命令:yarn add axios 或者 npm install axios

二、无状态组件

概念:无状态组件顾名思义就是没有状态的组件,如果一个组件不需要管理 state 只是纯的展示,那么就可以定义成无状态组件

(个人理解就是只有reder和dom就可以改变为无状态组件)

三、代码实例

请先学习Redux的使用https://blog.csdn.net/qq_17025903/article/details/102628320

ShowList.js

import React,{ Component } from 'react';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import { Input,Button,List  } from 'antd';
import store from '../store';
import ShowListUI from '../UI/ShowListUI';
import {CHANGE_INPUT_VALUE,ADD_TODO_ITEM,DELETE_TODO_ITEM,INIT_LIST_ACTION} from '../store/actionTypes';
import {getInputChangeAction,getAddItemAction,getDeleteItemAction,initListAction} from '../store/actionCreators';
import axios from 'axios';

//全局数据
// const data = [
//   'Racing car sprays burning fuel into crowd.',
//   'Japanese princess to wed commoner.',
//   'Australian walks 100km after outback crash.',
//   'Man charged over missing wedding girl.',
//   'Los Angeles battles huge wildfires.',
// ];

class showList extends Component{
  constructor(props){
    super(props);
    //创建数据
    this.state=store.getState();
    this.handleInputChange=this.handleInputChange.bind(this);
    this.handleStoreChange=this.handleStoreChange.bind(this);
    this.handleBtnClick=this.handleBtnClick.bind(this);
    this.handleItemDelete=this.handleItemDelete.bind(this);
    //监听返回组件的数据,并且同步数据。
    store.subscribe(this.handleStoreChange);
  }
  render(){
    return(
        <ShowListUI inputValue={this.state.inputValue} list={this.state.list} handleInputChange={this.handleInputChange}  handleBtnClick={this.handleBtnClick} handleItemDelete={this.handleItemDelete}></ShowListUI>
    )
  }

  // render(){
  //   return(
  //     <div style={{marginTop:'10px',marginLeft:'10px'}}>
  //       <div>
  //         {/*antd Input文本框*/}
  //         <Input value={this.state.inputValue} placeholder="Basic usage" style={{width:'300px', marginRight:'10px'}} onChange={this.handleInputChange}/>
  //         {/*antd button按钮*/}
  //         <Button type="primary" onClick={this.handleBtnClick}>提交</Button>
  //         {/*列表*/}
  //         <List style={{marginTop:'10px',width:'300px'}}
  //               bordered
  //               dataSource={this.state.list}
  //               renderItem={(item,index) => (
  //                 <List.Item onClick={this.handleItemDelete.bind(this,index)}>
  //                   {item}
  //                 </List.Item>
  //               )}
  //         />
  //       </div>
  //     </div>
  //
  //   )
  // }
  componentDidMount(){
    axios.get('http://localhost:8080/20190124_V1.0_SpringBoot/user/queryAllUserInfo').then((res)=>{
      const data=res.data;
      const newState=JSON.parse(JSON.stringify(data[0].age))
      console.log(res);
      console.log(res.data);
      const action=initListAction(data);
      console.log(action);
       store.dispatch(action);


    })
  }

  //action
  handleInputChange(e){
/*    const action={
      type:CHANGE_INPUT_VALUE,
      value:e.target.value
  };*/
    const action=getInputChangeAction(e.target.value);
    //action传递到store
    store.dispatch(action);
  }
  //点击提交添加到列表
  handleBtnClick(){
/*    const  action={
      type:ADD_TODO_ITEM
    };*/
    const action= getAddItemAction();
    store.dispatch(action);
  }
  //删除列表点击的内容
  handleItemDelete(index){
    // const action={
    //   type:DELETE_TODO_ITEM,
    //   index:index
    // }
    const action= getDeleteItemAction(index);
    store.dispatch(action);
  }
  //同步数据
  handleStoreChange(){
    this.setState(store.getState)
  }
}
export default  showList;

antdList.js

import React from 'react';
import ShowList from '../components/ShowList';

export default function() {

  return (
    <div>
      <ShowList></ShowList>
    </div>
  );
}

创建UI文件夹,拆分dom为ShowListUI.js

redux store 为index.js

//store 存数据传递reducer处理
import {createStore} from 'redux';
import reducer from './reducer';

import React from "react";
//window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() 为 redux devtools工具配置
const store=createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

export default store;

reducer.js

扫描二维码关注公众号,回复: 10213333 查看本文章

import {CHANGE_INPUT_VALUE,ADD_TODO_ITEM,DELETE_TODO_ITEM,INIT_LIST_ACTION} from '../store/actionTypes';
import TodoItem from "@/components/TodoItem";
import React from "react";
//reducer可以接收state但是不能修改state
//处理数据
//defaultState store默认值
const defaultState={
  inputValue:'123',
  list:[1,2]
}
//state上一次存储的数据
//action传过来改变的
export default (state=defaultState,action)=>{
 console.log(state,action);
 if(action.type===CHANGE_INPUT_VALUE){
   //复制一份数据
    const newState=JSON.parse(JSON.stringify(state))
   //修改
    newState.inputValue=action.value;
    return newState;
 }
 //添加到列表
 if(action.type===ADD_TODO_ITEM){
   const newState=JSON.parse(JSON.stringify(state))
   newState.list.push(newState.inputValue);
   newState.inputValue='';
   return newState;
 }
  //删除点击列表内容
  if(action.type===DELETE_TODO_ITEM){
    const newState=JSON.parse(JSON.stringify(state))
    newState.list.splice(action.index,1);
    return newState;
  }
  if(action.type===INIT_LIST_ACTION){
    //复制一份数据
    const newState=JSON.parse(JSON.stringify(state))
    newState.list2=[ ...newState.list];
    action.data.map((item)=>{
      newState.list2.push(item.age);
    })

    newState.list=newState.list2;

    return newState;
  }

  return  state;
}

actionTypes.js

//定义常量
export const CHANGE_INPUT_VALUE='change_input_value';
export const ADD_TODO_ITEM='add_todo_item';
export const DELETE_TODO_ITEM='delete_todo_item';
export const INIT_LIST_ACTION='init_list_action';

actionCreators.js

import {CHANGE_INPUT_VALUE,ADD_TODO_ITEM,DELETE_TODO_ITEM,INIT_LIST_ACTION} from '../store/actionTypes';

export const getInputChangeAction=(value)=>({
  type:CHANGE_INPUT_VALUE,
  value:value
});
export const getAddItemAction=()=>({
  type:ADD_TODO_ITEM
});
export const getDeleteItemAction=(index)=>({
  type:DELETE_TODO_ITEM,
  index:index
});


export const initListAction=(data)=>({
  type:INIT_LIST_ACTION,
  data:data
});

请求的接口为springboot的 queryAllUserInfo

四、完成结果

list:[1,2]数组添加了请求服务的age,并且可以点击删除。

发布了117 篇原创文章 · 获赞 32 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/qq_17025903/article/details/102796367
今日推荐