使用过时的状态在渲染中反应传递道具

时间:2021-06-01 22:55:36

标签: javascript reactjs redux

在我的 React 类的构造函数中,我调用了我的 API。我使用来自我的 API 的数据来更改我的类的状态,并且来自我的状态的信息作为道具传递给我在渲染方法中拥有的组件。

我的构造函数:

   constructor(props){
    super(props)
  
    this.state = {
        description:"",
        amount: 0,
        createdAt: 0,
        note:"",
    }
    
   
   this.callAPI() 
   

}

如您所见,我使用 callAPI 方法调用我的 API。 这里是 callAPI()

callAPI(){
  
    const expenseID = this.props.match.url.substring(19, this.props.match.url.length);

    let url = "http://localhost:8080/singleExpense?email="+encodeURIComponent(this.props.email)+"&id="+encodeURIComponent(expenseID)
  
    let h = new Headers({
        "Authorization": this.props.token
    })
    let req = new Request(url, {
        method: "GET",
        headers: h
    })
    fetch(req).then(async(response,error)=>{
        if(error){
            console.log(error)
            return
        }
        const parseResponse = await response.json()
       
        this.setState(()=>{
            return({
                description: parseResponse.description,
                amount: parseResponse.amount,
                createdAt: parseResponse.createdAt,
                note: parseResponse.note
            })
        })
        console.log(this.state)
    })
}

我获取一些数据并更新我的状态

这是我的渲染方法

 render(){
   
    
    return(
        <div>
            <ExpensForm description = {this.state.description} amount = {this.state.amount} createdAt = {this.state.createdAt} note = {this.state.note}/>
        </div>
    )
}

我作为道具传递的描述和数量等道具不是来自 API 调用更新状态的道具,而是默认的道具。

如何制作它以便我可以从我的 API 获取数据,更新状态,然后将其作为道具传递给我在渲染方法中使用的组件。

如果您需要任何其他信息,请告诉我。

根据要求,费用表单组件的构造函数

export default class ExpenseForm extends React.Component {

constructor(props){
    super(props)
    console.log(props)
    this.state = {
        description: props?props.description:"",
        note: props.expense?props.expense.note:"",
        amount: props.expense?(props.expense.amount/100).toString():"",
        createdAt: props.expense?moment(props.expense.createdAt) :moment(),
        calendarFocused: false,
        errorState: ""
    }
}

0 个答案:

没有答案