鍍金池/ 問答/HTML/ react中關(guān)閉模態(tài)框,如何實(shí)現(xiàn)組件更新?

react中關(guān)閉模態(tài)框,如何實(shí)現(xiàn)組件更新?

clipboard.png

頁面中進(jìn)行點(diǎn)擊保存,ajax請求會成功后,關(guān)閉模態(tài)框,如何能夠自動的在父組件中實(shí)現(xiàn)刷新?
如果用this.setState,父組件中的數(shù)據(jù)都是ajax請求回來遍歷出來的,不了解在哪個(gè)部分設(shè)置this.setState。
附上代碼:感謝好心人~


父組件代碼:HostActionList.jsx
import React, { Component, PropTypes } from 'react'
import { Link, withRouter } from "react-router"
import { Tooltip, Popconfirm, Form, Select, Modal, message } from "antd"
const FormItem = Form.Item;
const Option = Select.Option;
import ajax from "../../common/ajax"
import Auth from "../../common/Auth"
import { Action, ActionList } from "../../common/Actions"
import ReadModal from "./HostReadModal"
import UpdateModal from "./HostUpdateModal"


@withRouter
export default class MyActionList extends React.Component {
  constructor(props) {

    super(props);
    this.state = {
      readModalShow: false,
      updateModalShow:false,
      statusList:''
    }
  }



  handleDelete() {
    const {itemId, item, reload} = this.props
    console.log(item[itemId] )
    ajax({
      url: "/ndasec/host/delete.do",
      type: "post",
      data: { host_id: item[itemId] },
      success: p => {
        if (p.success) {
          message.success(p.msg);
          reload();
        } else {
          message.error(p.msg)
        }
      }
    })
  }

  handleRead() {
    this.setState({ readModalShow: true })
    const {itemId, item, reload} = this.props
        // console.log(item[itemId] )
        // console.log(this.props)
    console.log(this.props.item)
    ajax({
      url: "/ndasec/host/detail.do",
      type: "post",
      data: { host_id: item[itemId] },
      success: p => {
        if (p.success) {
           console.log(p.data)
          this.setState({
            statusList:p.data
          })
        } else {
          message.error(p.msg)
        }
      }
    })
  }

  handleUpdate(data) {
    this.setState({ updateModalShow: true })
    const {itemId, item} = this.props
    console.log(item.host_id)
    ajax({
      url: "/ndasec/host/detail.do",
      type: "post",
      data: { host_id: item[itemId] },
      success: p => {
        if (p.success) {
          // console.log(p.data)
          this.setState({
            statusList:p.data
          })
        } else {
          message.error(p.msg)
        }
      }
    })
  }


  render() {
    const {readModalShow,updateModalShow}=this.state
    const {item, reload} = this.props
    const {is_system: isSystem} = item



    const DeleteAction = () => (
      <Auth code="host-delete">
        <Action tooltip="刪除"
          icon="fa-remove"
          confirm="確定要刪除?"
          onOk={this.handleDelete.bind(this)}
          />
      </Auth>
    )

    const UpdateAction = () => (
      <Auth code="template-policy-host-data-edit">
        <Action tooltip="編輯"
          icon="fa-edit"
          onOk={this.handleUpdate.bind(this)}
          />
      </Auth>
    )

    const ReadAction = () => (
      <Auth code="template-policy-host-data-detail">
        <Action tooltip="查看"
          icon="fa-search"
          onOk={this.handleRead.bind(this)}
          />
      </Auth>
    )

    let actions
    if (isSystem == 1) {
      actions = [ReadAction]
    } else {
      actions = [ReadAction, UpdateAction, DeleteAction]
    }

    return (
      <ActionList>
        {actions.map((E, i) => <E key={i}></E>)}
        {readModalShow &&
        <ReadModal statusList={this.state.statusList} done={() => this.setState({ readModalShow: false, reload: true })}/>
        }
        {updateModalShow &&
        <UpdateModal statusList={this.state.statusList} done={() => this.setState({ updateModalShow: false, reload: true })}/>
        }
      </ActionList>
    )
  }
}
子組件代碼:HostUpdateModal.jsx

import * as React from "react";
import { Link, withRouter } from "react-router";
import { Form, Input, Button, Select, Radio, DatePicker, TimePicker, Checkbox, Table, Modal, Upload, Alert,message } from "antd";
import ajax from "../../common/ajax.js";
import s from "../../Main/Template/ImportModal.less";
import auth from "../../common/authService.js"
const {Dragger} = Upload;
const FormItem = Form.Item;
const { Option } = Select

@Form.create()
export default class extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      visible: true,
      statusList: []
    }
  }

  cancelUpdate=()=> {
    this.props.done();
  }



  handleReset=(e)=> {
    e.preventDefault();
    const { form } = this.props;
    form.resetFields();
    this.props.done();
  }

  handleSubmit(e){
    e.preventDefault();
    const { form } = this.props
    form.validateFields((errors, values) => {
      console.log(values)
      if (!!errors) {
        return;
      }
      this.updateHost(values);
    });
  }

  ajaxSuccess = p => {
    if (p.success) {
      console.log(p)
      console.log(this.props.statusList)
      message.success(p.msg);
      this.forceUpdate();
      this.props.done();
      //this.props.router.replace('/main/hello/host_list');

    } else {
      message.error(p.msg);
    }
  }




  updateHost(values){
    console.log(values);
    console.log(this.props.statusList.system_id)
    console.log(this.props.statusList.weight)
    console.log(values.system_id)
    this.setState({ isDoingSubmit: true })
    ajax({
      url: "/ndasec/host/edit.do",
      type: "post",
      data: {
        "host_id":this.props.statusList.host_id,
        "host_name":values.host_name,
        "host_ip": values.host_ip,
        "user_id": values.user_id,
        "system_id": values.system_id==="Windows XP"?1:values.system_id==="Windows 2000"?2:values.system_id==="Windows 2003"?3:values.system_id==="Windows 2008"?4:values.system_id==="Windows Vista"?5:values.system_id==="Windows 7"?6:values.system_id==="Windows 8"?7:8,
        "weight":values.weight==='低'?1:values.weight==='中'?2:3,
        "host_manager":values.host_manager,
        "manager_dept":values.manager_dept,
        "manager_email":values.manager_email,
        "manager_phone":values.manager_phone,
        "remark":values.remark
      },
      success:this.ajaxSuccess
    })
  }

  componentaDidMount(){
    const {  statusList } = this.state;
    ajax({
      url: "/ndasec/operatingsystem/queryList.do",
      type: "post",
      data:{system_id:this.props.statusList.system_id},
      success: (payload) => {
        if (payload.success) {
          const { data } = payload;
          this.setState({
            statusList: statusList.concat(data.map(e => ({ id: e.system_name, name: e.system_name }))),
            systemName:payload.data[0].system_name
          })
        }
      }
    })
  }


  render() {
    const {targets} = this.props
    const {form} = this.props;
    const {getFieldProps} = form;
    const {successMsg, errorMsg} = this.state;



    const footer = (
      successMsg &&
      <Alert message={successMsg} type="success" showIcon closeText="確定" onClose={this.cancelUpdate.bind(this)} />
      || errorMsg &&
      <Alert message={errorMsg} type="error" showIcon closeText="確定" onClose={this.cancelUpdate.bind(this)} />
    )

    return (
      <Modal className={s.modal}
             title="修改主機(jī)詳情"
             visible={true}
             okText="確認(rèn)"
             cancelText="取消"
             onCancel={this.cancelUpdate.bind(this)}
             footer={footer}
      >
        <Form>
          <FormItem
            label="主機(jī)名稱"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
            help='不能為空 / 長度不超過30個(gè)字符 / 不能輸入重復(fù)任務(wù)名稱/不能包含 / : * ? " < > |'
          >
            <Input
                   {...getFieldProps("host_name",{
                     initialValue: this.props.statusList.host_name,
                     rules:[{
                       required: true, message: '請輸入您的主機(jī)名稱~',
                     }]
                   }) }

            />
          </FormItem>
          <FormItem
            label="目標(biāo)IP"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
          >
            <Input
                   {...getFieldProps("host_ip",{
                     initialValue: this.props.statusList.host_ip,
                     rules:[{
                       required: true, message: '請輸入目標(biāo)IP的地址~',
                     }]
                   }) }
            />
          </FormItem>
          <FormItem
            label="用戶ID"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
          >
            <Input
                   {...getFieldProps("user_id") }
            />
          </FormItem>
          <FormItem
            label="操作系統(tǒng)"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
          >
            <Select
              placeholder="請選擇操作系統(tǒng)"
              {...getFieldProps("system_id",{
                initialValue:this.state.systemName
              })
              }
            >
              {this.state.statusList.map(e => <Option value={e.id.toString()} key={e.id}>{e.name}</Option>)}
            </Select>
          </FormItem>
          <FormItem
            label="權(quán)重"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
          >
            <Select
              showSearch
              optionFilterProp="children"
              notFoundContent="無匹配項(xiàng)"
              {...getFieldProps("weight",{
                initialValue:this.props.statusList.weight===1?'低':this.props.statusList.weight===2?'中':'高'
              })
              }
            >
              <Option value="高">高</Option>
              <Option value="中">中</Option>
              <Option value="低">低</Option>
            </Select>
          </FormItem>
          <FormItem
            label="主機(jī)管理員"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
          >
            <Input
                   {...getFieldProps("host_manager",{
                     initialValue: this.props.statusList.host_manager,
                     rules:[{
                       required: true, message: '請輸入主機(jī)管理員姓名哦~',
                     }]
                   }) }
            />
          </FormItem>
          <FormItem
            label="管理員部門"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
          >
            <Input
                   {...getFieldProps("manager_dept",{
                     initialValue: this.props.statusList.manager_dept,
                   }) }
            />
          </FormItem>
          <FormItem
            label="管理員郵箱"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
          >
            <Input
                   {...getFieldProps("manager_email",{
                     initialValue: this.props.statusList.manager_email,
                     rules:[{
                       type: 'email', message: '郵箱格式不正確,請重新輸入',
                     },{
                       required: true, message: '請輸入您的郵箱哦~',
                     }]
                   }) }
            />
          </FormItem>
          <FormItem
            label="管理員手機(jī)號"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
          >
            <Input
                   {...getFieldProps("manager_phone",{
                     initialValue: this.props.statusList.manager_phone,
                     rules:[{
                       required: true,whitespace: true,message:'電話號碼需要符合規(guī)則'
                     },{ validator: this.checkPhone }],
                   }) }
            />
          </FormItem>
          <FormItem
            label="備注"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
          >
            <Input
                   {...getFieldProps("remark",{
                     initialValue: this.props.statusList.remark,
                   }) }
            />
          </FormItem>

        </Form>

        <div style={{ textAlign: 'right' }}>
          <Button onClick={this.handleSubmit.bind(this)} style={{marginRight:'10px'}}   type="primary" htmlType="submit">保存</Button>
          <Button onClick={this.handleReset.bind(this)}>返回</Button>
        </div>

      </Modal>
    )
  }
}
回答
編輯回答
憶往昔

clipboard.png
點(diǎn)擊了模態(tài)框中的提交后,重新請求了數(shù)據(jù)列表。但是獲取到的數(shù)據(jù)列表中的值,如何賦給父->父組件中?

clipboard.png

2017年7月28日 01:34
編輯回答
笑忘初

修改下state行不行,只要state改變了就會觸發(fā)render

2018年6月4日 21:58
編輯回答
笑忘初

刷新沒有自動,都是手動,所以才要代碼實(shí)現(xiàn)。

手動刷新是什么邏輯呢?重新請求列表接口。

怎么請求列表接口呢?肯定是一個(gè)函數(shù)了~

那么,現(xiàn)在邏輯很清楚了,關(guān)閉模態(tài)框,請求列表接口,刷新。

用代碼把這個(gè)邏輯串起來,很簡單,你來試一下。

2018年4月12日 18:33
編輯回答
厭惡我

在點(diǎn)擊保存調(diào)用添加接口后判斷調(diào)用父組件查詢接口不就刷新了嗎

2017年11月1日 01:54
編輯回答
筱饞貓

重新請求列表

2018年3月1日 14:05