【发布时间】:2021-08-13 10:35:37
【问题描述】:
我知道 setState 无法立即使用,因为它处于挂起状态。因此,我尝试按照建议使用箭头功能执行 console.log,并且在“desiredIncome”状态下它可以工作,但不是在“total”下。它已更新并仅在第二次提交后显示。
import React, { Component } from 'react'
import styled from 'styled-components'
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { fetchHealthCare, fetchConsumerGoods, fetchEnergy, fetchFinance } from '../actions';
import './Input.css';
export class Input extends Component {
componentDidMount(){
this.props.fetchHealthCare(this.props.id);
this.props.fetchConsumerGoods(this.props.id);
this.props.fetchEnergy(this.props.id);
this.props.fetchFinance(this.props.id);
}
constructor(props){
super(props);
this.state = {
desiredIncome: 0,
total: 0
}
}
renderInput = formProps => {
return <input
onChange={formProps.input.onChange}
value={formProps.input.value}
placeholder=" Enter your desired monthly income" />
}
healthSum = () => (this.state.desiredIncome * 100) / this.props.healthCare.dividendYield;
consumerGoodsSum = () => (this.state.desiredIncome * 100) / this.props.consumerGoods.dividendYield;
energySum = () => (this.state.desiredIncome * 100) / this.props.energy.dividendYield;
financeSum = () => (this.state.desiredIncome * 100) / this.props.finance.dividendYield;
onSubmit = formValues => {
this.setState({desiredIncome: ((formValues.sum * 12) / 4) / 4}, () => {
console.log(this.state.desiredIncome);
});
this.setState({total: this.healthSum() + this.consumerGoodsSum() + this.energySum() + this.financeSum()}, () => {
console.log(this.state.total);
})
}
render(){
return (
<React.Fragment>
<Container>
<Display>
<form autoComplete="off" onSubmit={this.props.handleSubmit(this.onSubmit)} >
<Field name="sum" component={this.renderInput} />
</form>
<List>
{this.check()}
</List>
</Display>
</Container>
<h3 className="footer">Made by Tursynbek Bauyrzhan</h3>
</React.Fragment>
)
}
我该如何解决?
【问题讨论】:
-
你可以在setState之前控制台一次
this.healthSum() + this.consumerGoodsSum() + this.energySum() + this.financeSum()的值
标签: javascript reactjs react-redux submit setstate