zoukankan      html  css  js  c++  java
  • react 问题记录二(侧重于state或者说server层操作)

     项目体系说明:react+mobx+antd

     11. state设置对象属性

     this.setState({
          tableParams:{tableName:value}
        })

    10.loading组件设置

    this.setState({
              title: Utils.trim(query.title),
              loading:true,
            });
            
            this.props.articleService.findPage(query, true)
              .then(data => this.setState({loading: false}))
              .catch(e => this.setState({loading: false}));

    9.模态框弹出时,需要传递参数应该怎么设置?

    showModal = (obj,b) => {
    
        this.setState({
          visible: true,
          oldTopicId: obj.id,
        });
        console.log("a==============" ,obj);
    
        console.log("b==============" ,b);
        // 获取主题词下所有关键词的id集合
        const myParams = {};
        myParams.topicId = obj.id;
        this.topicState.getKeyWordIds(myParams);
      };
    
    
    
    //---------------------------------------------------------------------------
    const columns = [{
          title: '主题',
          dataIndex: 'name',
          key: 'name',
        }, {
          title: '关键词',
          dataIndex: 'keywords',
          key: 'keywords',
          render: (item) => item ? item.join(',') : ''
        }, {
          title: '操作',
          key: 'operation',
          render: (_, record) => (
            <div>
              <Link to={`/topic/${record.id}`}><Icon type="edit"/>编辑</Link>
              <span className="ant-divider"/>
                <a className="fgw-text-error" onClick={this.showModal.bind(this, record)}><Icon type="delete"/>删除</a>
    
            </div>)
        }];

    8.当切换路由后(切换了左侧导航栏后),用户在返回之前查询的结果界面,结果界面还会展示上一次的结果,应该如何处理呢?

    //第一步
    
    componentWillUnmount() {

    this.props.store.docClassifyState.clearClassifyResult();
    }



    //第二步,在对应的state里面写一个清空数据源的函数 /* * 清空已有的数据源 * */

    clearClassifyResult(){
    this.setClassifyResult({});
    }
    
    

    7.Input.Search组件下,如何配合分页组件传递搜索框中的参数

    constructor(props) {
        super(props);
        this.state = {
          params: '',
        };
        this.store = this.props.store.websiteState;
      }
    
    
    const paginationProps = {
          pageSize: size || 0,
          currentPage: number || 0,
          totalElements: totalElements || 0,
          showSizeChanger: true,
          onChange: (page, size) => {
            this.store.getWebsitePage({page, size, name: this.state.params});
          }
        };
    
    
    
    <Input.Search placeholder="输入网站名称或网址进行搜索"
                                  onSearch={value =>{
                                    if (value === this.state.params) {
                                      return
                                    }
                                    this.setState({params: value});
                                    this.store.getWebsitePage({name: value})
                                  }}/>

     

    6.需要更新用户信息时,需要把用户原来的信息一起传回给后台,这个时候推荐下面的写法,首先

    this.userState.user这个是数据源,然后...values 这个是表单中变化的值,通过新的值来覆盖旧的值,达到更新数据的操作。

     

     

    if (tag === 'user') {
              this.userState.updataUser({...this.userState.user,...values});//更新用户信息
            }

     

     

     

     

    5.业务场景:当用户添加一条数据,比如添加一个用户,但是用户名已经存在了,这个时候需要提示给用户并停留在当前的编辑界面,当操作成功后,跳转到table列表界面上

    主要说明两点,其一异步操作,其二,state里面注意需要添加 return date的操作:

     

    //state
    //修改一条数据
      async updataRoom(value) {
        const {data} = await request(
          {
            method: 'put',
            url: '/api/room',
            data: value
          },
          {message: '保存成功'},
          {message: '保存失败'},
        );
        this.setRoom(data);
        return data;//重要
      }
    
    
    //异步调用
    
    handleSubmit = (e) => {
            e.preventDefault();
            this.props.form.validateFieldsAndScroll((err, values) => {
                if (!err) {
                    console.log('Received values of form: ', values);
                    if (this.isAdd()) { //新增
                        this.roomState.createRoom(values).then((response)=> {
                  //取到后台的返回 response 根据其中一个不为空的值做判断条件 const {status}
    = response; debugger; console.log('response',status); if(status){ Utils.goBack(); } }) } else { values.roomId = this.props.match.params.id; console.log('values of form: ', values); this.roomState.updataRoom(values).then((response)=> { console.log('response',response); const {status} = response; if(status){ Utils.goBack(); } }); //修改 } } }); };

     

     

     

     

    4.执行删除操作后,界面重新查询一次,就是把删除后的效果呈现出来的操作模式

     

      /*
       * 根据主机Id删除主机
       * /api/host/{hostId}
       * */
      async deleteRemoveHost(hostId,cabinetId) {
        const {data} = await request(
          {method: 'DELETE', url: `/api/host/${hostId}/remove`},
          {message: '移除成功'},
          {message: '移除失败'},
        );
        this.getCabinetHost(cabinetId);
      }
    
    }

     

     

     

     

    3.当state状态发生改变会引发界面的重绘,即使数据改变会实现界面的重新渲染。这个思想比较重要,做说明一下(

    this.setState({host: host});

    )

    constructor(props) {
            super(props);
          this.state ={
            cabinetId: '',
            hostId: '',
            host:{},
          };
            this.cabinetState = this.props.store.cabinetState;
        }
    
    
    
    /*
      * 用户点击主机后,取出主机的详细信息展示在右侧
      * */
      handleClick = (host) =>{
        console.log('主机参数',host);
        this.state.host = host;
        this.setState({host: host});
        this.state.hostId = host.hostId;
        console.log('当前主机',this.state.host.hostId);
        //this.renderParameter(host)
      };
    
    
     renderParameter =()=>{
        const hostObj = this.state.host;
        if(hostObj === null || hostObj ===undefined || !hostObj.hostId){
          return <div><h3 className="fgw-margin-bottom-20">请点击右侧主机,可查看主机的详情信息</h3></div>
        }
        console.log('主机参数',hostObj);
        console.log('服务参数', eval('('+hostObj.info+')'));
        //console.log('服务参数', JSON.stringify(hostObj.infos));
        //console.log('服务参数', JSON.parse(hostObj.infos));
    
        const info = eval('('+hostObj.info+')');
        return(
    <div>
            <Col span={12}>
              <label className="hl-font-20">设备名称:</label>
              <span>{hostObj.hostId}</span>
            </Col>
    </div>
        
    )
       )
      };

     

     

     

    1. react提交按钮响应回车事件(基于react+Mobx的实现模式)
      handleSubmit = (e) => {
              e.preventDefault();
              this.props.form.validateFieldsAndScroll((err, values) => {
                  if (!err) {
                      console.log('Received values of form: ', values);
                      if (e.keyCode == 13)//回车键的键值为13
                      {
                          e.returnValue=false;
                          e.cancel = true;
                          this.store.getPolicyPage(values);//调用按钮的事件
                      }
                      this.store.getPolicyPage(values);
                  }
              });
          };

       

    2. renderHotFont =()=>{
              const hotFont = this.store.wordList;
              console.log("wordList",this.store.wordList);
              console.log("systemList",this.store.systemList.value);
      
      
      
              /*const sysList = [];
              for (itme of this.store.systemList){
      
              }*/
      
              const sysList = this.store.systemList.map(function (item) {
                  return (item.value);
              });
              let myList = [];
              if(sysList.length > 0){//做非空判断
                  myList = sysList[0].split(',');//字符串转成数组
              }
      
              if (!this.store.systemList) {
                  return <div style={{textAlign: 'center', paddingTop: '30px'}}>暂无关键词</div>
              }
              return myList.map(doc => {
                  const keyWord = this.store.wordList.find(temp => temp.id === doc);//从所有的关键词中获取对应的名字
                  debugger;
                  return (<div className="fgw-word">{keyWord.name}</div>)
              });
      
      
      
              /*if (!this.store.wordList) {
                  return <div style={{textAlign: 'center', paddingTop: '30px'}}>暂无关键词</div>
              }
              return this.store.wordList.map(doc => {
                  return (<div className="fgw-word">{doc.name}</div>)
              });*/
          };

       

    3. //日期比较大小(开始时间不能大于结束时间约束)
      
      let params = {};
                          params.startTime = values.startTime.format('YYYY-MM-DD');
                          params.endTime = values.endTime.format('YYYY-MM-DD');
                          console.log('开始时间', params);
                          if(Date.parse(params.endTime) - Date.parse(params.startTime) <= 0){
                              Modal.error({//使用模态框的error模式,需要引入对应的组件
                                  title:'提示消息',
                                  content:'开始时间不能大于结束时间'
                              });
                              return;
                          }

       

     

  • 相关阅读:
    java多线程
    golang编码转换
    golang csv,xls,xlsx
    golang 资源
    electron安装
    Ubuntu系统下面软件安装更新命令
    golang代码执行顺序
    datatables使用
    Echarts柱形图颜色设置
    golang chan 超时
  • 原文地址:https://www.cnblogs.com/zxyun/p/7079138.html
Copyright © 2011-2022 走看看