react项目经验

本文详细介绍了在React项目中遇到的各种实践经验,包括页面跳转与刷新、接口调用、状态管理、组件交互等。重点讲解了如何读懂接口文档、使用axios进行请求、动态添加组件以及处理搜索框数据。同时,还探讨了React组件内外代码的组织和函数参数判断等问题。
摘要由CSDN通过智能技术生成
调用后返回上一页&&跳转至当前页
 this.props.history.goBack();   返回
 this.props.history.push("/index/setting/basicsetting"); 跳转
 this.props.history.go(-1)  跳转

当使用时出现以下错误Cannot read property 'push' of undefined,
因为父组件调用子组件定义的跳转事件时,要传递history,这里history未定义
(比如app.js这个组件,一般是首页,不是通过路由跳转过来的,而是直接从浏览器中输入地址打开的,如果不使用withRouter此组件的this.props为空,没法执行props中的history、location、match等方法)
解决方法:
import React from "react";
import {withRouter} from "react-router-dom";   //第一,引入withRouter

class MyComponent extends React.Component {   
  ...
  myFunction() {
    this.props.history.push("/some/Path");
  }
  ...
}
export default withRouter(MyComponent);   //第二,不要在上面暴露模块,在这里使用withRouter暴露模块

详细可见:react-router v4 使用 history 控制路由跳转   https://github.com/brickspert/blog/issues/3
调用后重新渲染当前页&&跳转至当前页
 this.props.history.go(0)  跳转



 state={
   visible:false
 }
 handleClick=()=>{
    this.setState({
       visible:true
     });
   }
 this.setState(this.state)  //此语句执行过后页面重新渲染state。这里需要注意的事重新渲染会将visible渲染成state里的false,而不是handleClick里的true
//渲染会把state里的内容全部重新渲染,即执行this.setState(state)之后,visible会被重新渲染为false,若需要visible为true,可以在渲染之后重新定义状态,如下重新定义
 this.setState({this.state})
 this.setState({
      visible:true
   });



 定义componentWillMount=async()=>{   
        this.getData(); //重新渲染当前页面
    }  // 使用:调用this.getData();函数即可
    async getData(){
        代码段
    }
代码解析
let {state}=this;  // 即 let state = this.state;

let res = await api.SettingGetInfo(this.props.match.params)   //获取二维码列表当前二维码的id值,此方法需要注意在route页面里的route添加  /:id
//即<Route path="/index/setting/basicsetting/:id" component={BasicSettting} />


rowKey={record=>record.id}    //表格table中的每个记录应该有唯一的“key”支持,或者将“rowKey”设置为唯一的主键,否则会报错。这里是给表格设置rowKey
点击按钮复制相关内容(这里以复制链接为例)
  npm i --save copy-to-clipboard   //首先安装相关包

  import copy from 'copy-to-clipboard';  //引入模块

  render:(a, code, index)=>{
                return <span>
                    <a href="# "  onClick={()=>{this.copyLink(code)}}>复制链接</a>
                </span>
            }

  copyLink=(code)=>{
        copy(`https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${code.info}`)
        message.success("链接复制成功",2.5)
    }
三目运算符的嵌套使用
正常使用:code.type===1?(adate<bdate?atime:btime):<span className="text-success">永不</span>

react里:{title:"时间",dataIndex:"Time",render(a,code,index){
                let adate=...;
                letbdate=...;
                var overtime=<span className="text-danger">时间不足</span>;
                var forevertime=<span className="text-success">永久</span>
                var times=`${date.getFullYear()}-${date.getMonth() + 1<10?"0"+(date.getMonth()+1):date.getMonth()+1}-${date.getDate()<10?"0"+date.getDate():date.getDate()} ${date.getHours()<10?"0"+date.getHours():date.getHours()}:${date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes()}:${date.getSeconds()<10?"0"+date.getSeconds():date.getSeconds()}`   //将时间戳转换为日期格式

                return <span>{code.type===1?(adate<bdate?overtime:times):forevertime}</span>  //嵌套使用
            }}

======================================================================================================================================================

接口部分

读懂接口文档

/api/wechat/code/:officialId/:qrcodeId  带冒号,动态数据:`${base}/api/wechat/code/${localStorage.getItem("listid")}/${params.id}`  //这列的:qrcodeId需要使用${params.id}动态写入,params即数组
/api/wechat/statistics/:officialId/code  不带冒号,静态的:`${base}/api/wechat/statistics/${localStorage.getItem("listid")}/code`  //这里的qrcode直接写上去就可以
 
参数问题
  request<T = any>(config: AxiosRequestConfig): AxiosPromise<T>;   //request 一个参数  config
  get<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>;  //get  两个参数 url config
  delete(url: string, config?: AxiosRequestConfig): AxiosPromise;  //delete  两个参数  url config
  head(url: string, config?: AxiosRequestConfig): AxiosPromise;   //head  两个参数 url config
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>;  //post 三个参数 url data config
  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>; // put 三个参数 url data config
  patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>; // patch 三个参数 url data config

参数解释 :url —— 请求地址
                   data——发送给服务器的请求数据
                   config——配置,一般都是固定格式

举个栗子:
  e
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值