如何在函数内返回函数并在返回时显示它

时间:2019-09-27 13:12:45

标签: javascript reactjs

这是我的状态

    constructor(props) {
    super(props);
    this.state = {
        fToC: '',

这是我的功能

    handleChange = async (value) => {
    this.setState({ value });
    await Axios.get(`http://dataservice.accuweather.com/`).then((res) => {
        this.setState({ weather: res.data });

        console.log('weather_Temperature:' + this.state.weather.DailyForecasts[0].Temperature.Maximum.Value);

  >>>>>> function FToC(fahrenheit) { <<<<<<<<<<<<<<< 
            let fTemp = fahrenheit;
            let fToCel = (fTemp - 32) * 5 / 9;
            let message = fTemp + '\xB0F is ' + fToCel + '\xB0C.';
            console.log('message' + message);
        } FToC(this.state.weather.DailyForecasts[0].Temperature.Maximum.Value);
        this.setState({ FToC }) 

在这里,我想返回函数的结果

        <p class="card-text">{this.state.FToC}</p> 

错误:

警告:函数作为React子元素无效。如果返回Component而不是从render返回,则可能会发生这种情况。或者也许您打算调用此函数而不是返回它。

2 个答案:

答案 0 :(得分:4)

所以问题是您试图呈现设置为状态的函数

您需要从FToC函数返回一个值,然后在setState方法中调用它

setState({fToC: FToC(this.state.weather.DailyForecasts[0].Temperature.Maximum.Value))

顺便说一句,this.setState({FToC})在您的状态下创建了另一个字段(FToC),您已经有fToC

下面的代码应该很好用

handleChange = async (value) => {
    this.setState({ value });
    await Axios.get(`http://dataservice.accuweather.com/`).then((res) => {
        this.setState({ weather: res.data });

        console.log('weather_Temperature:' + this.state.weather.DailyForecasts[0].Temperature.Maximum.Value);

  function FToC(fahrenheit) {
            let fTemp = fahrenheit;
            let fToCel = (fTemp - 32) * 5 / 9;
            let message = fTemp + '\xB0F is ' + fToCel + '\xB0C.';
            return message;
        } ;
        this.setState({ fToC: FToC(this.state.weather.DailyForecasts[0].Temperature.Maximum.Value) }) ```

答案 1 :(得分:1)

如果我正确理解了您的愿望的意思。您的代码应该看起来像这样

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      weather: null
    }
   }
    
    componentDidMount() {
      this.handleChange();
    }
    
    handleChange = async() => {
      await Axios.get(`http://dataservice.accuweather.com/`)
        .then((res) => {
          this.setState({ 
            weather: res.data 
          });
        }
    }
    
    FToC(fahrenheit) { 
            let fTemp = fahrenheit;
            let fToCel = (fTemp - 32) * 5 / 9;
            let message = fTemp + '\xB0F is ' + fToCel + '\xB0C.';
            
            return message;
    }
    
    render() {
      const {weather} = this.state;
      
      if (!weather) return <div>Loading...</div>
      
      return (
        <p class="card-text">{this.FToC(weather.DailyForecasts[0].Temperature.Maximum.Value)}</p> 
      )
    }
}