react 问题记录二(侧重于state或者说server层操做)

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

 11. state设置对象属性web

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

 

 

 

10.loading组件设置api

 

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.当切换路由后(切换了左侧导航栏后),用户在返回以前查询的结果界面,结果界面还会展现上一次的结果,应该如何处理呢?antd

 

//第一步
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.须要更新用户信息时,须要把用户原来的信息一块儿传回给后台,这个时候推荐下面的写法,首先async

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

 

 

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

 

 

 

 

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

主要说明两点,其一异步操做,其二,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; }
相关文章
相关标签/搜索