提问者:小点点

从当前组件成功调用api后,向另一个react组件显示警报


我有tenanter组件,它负责列出所有租户的详细信息,例如:姓名,电话,租金等,我有addtenanter组件,它包含一个用于创建新租户的表单。

在我的AddTenanter组件中,我进行了一个api调用,以便在数据库中存储新的承租人信息,在api调用成功之后,我希望重定向到Tenanter组件并希望显示一个警报(此警报消息应在条件下显示)

到目前为止,我可以使用react-router重定向组件进行api调用并重定向到tenanter组件,但无法在条件下显示警报消息

租户组件

export default class Tenant extends React.Component {
    constructor(){
        super();
        this.state = {
            tenantList:[],
        }
    }

    componentDidMount(){
        
        axios.get("http://127.0.0.1:8000/api/tenants").then(response => {
            this.setState({
              tenantList: [...response.data.tenants]
            })
            //console.log(response)
          })
        //   if(this.props.location.state!== undefined){
        //       console.log('alert',this.props.location.state.msg)
        //       const {location,history} = this.props;
        //       history.replace() 
        //   }
    }

    render() {
        const {tenantList} = this.state

        // show alert on conditon
        var alert = ''
        if(this.props.location.state!==undefined){
            alert = <div class="alert alert-success" role="alert">
                        Success       
                    </div>
            const {location,history} = this.props;
            history.replace()
        }
        
      return (
        <div>
          <Header />
          <div id="layoutSidenav">
                <Sidebar />
                <div id="layoutSidenav_content">
                    <main>
                        <div class="container-fluid">
                            <h1 class="mt-4">Tenant</h1>
                            <ol class="breadcrumb mb-4">
                                <li class="breadcrumb-item"><Link to='/dashboard'>Dashboard</Link></li>
                                <li class="breadcrumb-item active">Tenant</li>
                            </ol>
                            {alert}
                            
                            <div class="card mb-4">
                                <div class="card-body">
                                    <Link class='btn btn-success mb-3' to='/tenant/create' >Create Tenant</Link>
                                    
                                    <div class="table-responsive">
                                        <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                                            <thead>
                                                <tr>
                                                    <th>Name</th>
                                                    <th>National ID</th>
                                                    <th>Phone Number</th>
                                                    <th>Registration Date</th>
                                                    <th>Expected Rent</th>
                                                    <th>House/Room No</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                                <tbody>
                                                    {tenantList.map(tenant=>(
                                                        <tr key = {tenant.id}>
                                                            <td>{tenant.name}</td>
                                                            <td>{tenant.nid}</td>
                                                            <td>{tenant.phone}</td>
                                                            <td>{tenant.reg_date}</td>
                                                            <td>{tenant.exp_rent}</td>
                                                            <td>{tenant.hrid}</td>
                                                            <td>
                                                            <Link class='btn btn-info ml-2' >Show</Link>
                                                            <Link class='btn btn-primary ml-2' >Edit</Link>
                                                            <Link class='btn btn-danger ml-2' >Delete</Link>
                                                            </td>
                                                        </tr>
                                                    ))}
                                                    
                                                </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </main>
                    <Footer />
                </div>
            </div>
        </div>
      );
    }
}

AddTenant组件

    const options = [
    { value: '101', label: '101' },
    { value: '102', label: '102' },
    { value: '103', label: '103' },
    { value: '104', label: '104' },
    { value: '105', label: '105' },
    { value: '106', label: '106' },
    { value: '107', label: '107' },
    { value: '108', label: '108' },
    { value: '109', label: '109' },
    { value: '110', label: '110' },
];



export default class AddTenant extends React.Component {
    constructor(props) {
        super(props);
        this.state ={
            startDate: moment(),
            nameInput: '',
            nidInput:'',
            nid_img:'',
            phoneInput:'',
            rentInput:'',
            hridInput:'',
            nameError: '',
            nidError:'',
            phoneError:'',
            rentError:'',
            hridError:'',
            errors:'',
            msg:'',
            redirect:false
        }
    }

    handleDateChange = (date)=>{
        this.setState({
            startDate: date
          })
        
    }
    handleFieldChange = (e)=>{ 
        this.setState({
            [e.target.name] : e.target.value
        })
        
    }
    handleDropDownMenu = (hridInput)=>{
        this.setState({ hridInput });
        console.log(`Option selected:`, hridInput);
    }

    validate = ()=>{
        let flag = true;
        let nameError = ""
        let hridError = ""

        if(!this.state.nameInput.includes(' ')){
            nameError = "Full name should contain a space"
            this.setState({nameError})
            flag = false
        }
        
        if(this.state.hridInput.value === undefined){
            hridError = "please select a house/room number"
            this.setState({hridError})
            flag = false
        }

        //datepicker validation is not done

        return flag

    }
    

    handleFormSubmit = (e)=>{
        e.preventDefault();
        
        let isValid = this.validate()

        if(isValid){
            console.log("form valid")
            const tenant = {
                name: this.state.nameInput,
                nid:this.state.nidInput,
                phone:this.state.phoneInput,
                exp_rent: this.state.rentInput,
                reg_date:moment(this.state.startDate).format("YYYY-MM-DD"),
                hrid:this.state.hridInput.value
            }
            //below line is commented because to test redirect component
            //console.log(tenant)
            // axios.post('http://127.0.0.1:8000/api/tenants', tenant)
            // .then(response => {
            //     // redirect to the homepage
            //     this.setState({redirect:true,msg:'success'})
            //     console.log(response);
                
            // })
            // .catch(error => {
            //     this.setState({
            //     errors: error.response.data.errors,msg:'failed'
            //     })
            // })
            this.setState({redirect:true,msg:'success'})
            this.setState({nameError:'',hridError:''})
        }
    }

    render() {
        if(this.state.redirect){
            return <Redirect to={{
                pathname: "/tenant",
                state : {msg:this.state.msg}
            }}/>
        }
      return (
        <div>
            <Header />
            <div id="layoutSidenav">
                <Sidebar />
                <div id="layoutSidenav_content">
                    <main>
                        <div className="container-fluid">
                            <h1 className="mt-4">Create Tenant</h1>
                            <ol className="breadcrumb mb-4">
                                <li className="breadcrumb-item"><Link to='/dashboard'>Dashboard</Link></li>
                                <li className="breadcrumb-item"><Link to='/tenant'>Tenant</Link></li>
                                <li className="breadcrumb-item active">Create Tenant</li>
                            </ol>
                            <div className="card mb-4">
                                <div className="card-body">
                                    <form onSubmit={this.handleFormSubmit} novalidate>
                                        <div className='form-group'>
                                            <label for="exampleInputEmail1">Full Name</label>
                                            <input type="text" className="form-control" id="nameInput" name="nameInput" value={this.state.nameInput} onChange = {this.handleFieldChange}  placeholder="Enter full name eg:Mahfuz Anam" required/>
                                            <div style={{fontSize:14, color:'red'}}>{this.state.nameError}</div>
                                        </div>
                                        <div className='form-group'>
                                            <label for="exampleInputEmail1">National ID</label>
                                            <input type="text" className="form-control" id="nidInput" name="nidInput" value={this.state.nidInput} onChange={this.handleFieldChange} placeholder="Enter national id" required/>
                                            
                                        </div>
                                        <div className='form-group'>
                                            <label for="exampleInputEmail1">National ID Image</label>
                                            <div className="input-group">
                                                <div className="input-group-prepend">
                                                    <span className="input-group-text" id="inputGroupFileAddon01">Upload</span>
                                                </div>
                                                <div className="custom-file">
                                                    <input type="file" className="custom-file-input" id="inputGroupFile01"
                                                    aria-describedby="inputGroupFileAddon01" />
                                                    <label className="custom-file-label" for="inputGroupFile01">Choose file</label>
                                                </div>
                                            </div>
                                        </div>
                                        <div className='form-group'>
                                            <label for="exampleInputEmail1">Phone Number</label>
                                            <input type="text" className="form-control" id="phoneInput" name="phoneInput" value={this.state.phoneInput} onChange={this.handleFieldChange} placeholder="Enter land/cell number" pattern="(^([+]{1}[8]{2}|0088)?(01){1}[3-9]{1}\d{8})$" required  />
                                            <div style={{fontSize:14, color:'red'}}>{this.state.phoneError}</div>
                                        </div>
                                        <div className='form-group'>
                                            <label for="exampleInputEmail1">Rent</label>
                                            <input type="number" className="form-control" id="rentInput" name="rentInput" value={this.state.rentInput} onChange={this.handleFieldChange} placeholder="Enter rent" 
                                             required/>
                                             
                                        </div>
                                        <div className='form-group '>
                                            <label for="exampleInputEmail1" style={{marginRight:'5px'}}>Registration Date</label>
                                            <DatePicker
                                                selected={ moment(this.state.startDate).toDate() }
                                                onChange={ this.handleDateChange }
                                                name="startDate"
                                                dateFormat="yyyy/MM/dd"
                                            />
                                            
                                        </div>
                                        <div className='form-group'>
                                            <label>House/Room No</label>
                                            <Select value={this.state.hridInput} options={options} onChange={this.handleDropDownMenu} required />                                           
                                            <div style={{fontSize:14, color:'red'}}>{this.state.hridError}</div>
                                        </div>
                                        <button className='btn btn-success'>Create</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </main>
                    <Footer />
                </div>
            
            </div>
        </div>
      );
    }
}

共1个答案

匿名用户

重定向时可以传递变量。

 //In AddTenant component
 history.push({
  pathname: '/tenant',
  yourCondition: conditionYouWantToPass,
 });

那么您可以将您的条件读为:

//In tenant component
this.props.location.yourCondition

或使用重定向:

render() {
    if(this.state.redirect){
        return <Redirect to={{
            pathname: "/tenant",
            state : {msg:this.state.msg, yourCondition : 
                     this.state.yourCondition}
        }}/>
    }

并在更新状态时更新条件状态。重定向:

this.setState({redirect:true,msg:'success'})
this.setState({nameError:'',hridError:''})
this.setState({yourCondition : yourCondition)

在租户组件中:

    // show alert on conditon
    var alert = ''
    if(this.props.location.state!==undefined){
        if(this.props.location.yourCondition) {
           alert = <div class="alert alert-success" role="alert">
                    Success       
                   </div>
           const {location,history} = this.props;
           history.replace()
        }
    }