如何在React中正确更新显示?

时间:2019-05-12 06:41:04

标签: reactjs

我一直在学习做出反应,之前我只是在用axios调用componentDidMount中的api,效果很好。
现在,此任务无需从api获取数据,因此我通常在componentDidMOunt中称为setState,但是由于setState是异步的,因此在需要时不会进行更新。
我想知道我应该怎么写,以减轻这个问题。这是一个简单的类代码。

    import React from 'react'
import CarCapacity from '../Components/TextBox/CarCapacity'
import randomHelper from '../Helper/randomCars'
import Row from 'react-bootstrap/Row'

class Parking extends React.Component{
    state={
        inText:null,
        cars:100,
        carDetails:[],
        remainingSlots:[]
    }

    numberOfcars=(event)=>{
        this.setState({inText:event.target.value})
    }

    updateFunc = ()=>{
        var details = randomHelper(this.state.cars)

        //setState is async therefore using a callBack to check if the state has been updated

        this.setState({carDetails:{...details}},function(){
            console.log(this.state.carDetails)
        })

    }



componentDidMount(){
    this.updateFunc()
}

componentDidUpdate(prevProps, prevState){
    if(prevState.cars!==this.state.cars){
        this.updateFunc()
    }
}

    setToCars=()=>{
        var st= this.state.inText;

        if(this.state.inText==null||st.trim()===""){
            alert("Cars cant be null")
        }
        else if(Number.isNaN(Number(this.state.inText))){
            alert("Enter a number")
        }
        else{
        this.setState({cars:this.state.inText})
        }
    }


    render(){

        console.log(this.state.carDetails)

        var carParkingFormation = this.state.carDetails.map((data, index)=>{
            var isCarParked = data.carNumber!==null? data.carNumber: "Not parked"
            var color = data.carColor!==null? data.carColor:" "
            var pos = data.carPosition

            return(
                <>
                    <Col md={4}>
                        <span>{isCarParked}</span>
                        <span>{color}</span>
                        <span>{pos}</span>
                    </Col>
                </>
            )
        })


        return(
            <>
            <CarCapacity carCapacity={this.numberOfcars} genCars={this.setToCars}/>
            <p>{this.state.cars}</p>
             <Row>
                {carParkingFormation}
             </Row>
            </>
        )
    }
}

export default Parking

在这里,由于setState beig async,在此carParkingFormation中,this.state.carDetail为null,因此,如何确保它按预期方式正常运行

1 个答案:

答案 0 :(得分:2)

您的carDetails是一个数组,您将其设置为updateFunc中的一个对象,因此在这种情况下,渲染中的贴图将无法在该对象上运行。尝试将其更改为以下内容:

this.setState({carDetails:[...details]},function(){
            console.log(this.state.carDetails)
        })