渲染上一个状态而不是下拉列表中选择的当前值

时间:2018-03-29 20:19:30

标签: javascript reactjs

我编写了下拉组件,通过回调函数将选定的值传递回父级。从那里我想简单地在下拉列表下面呈现所选值。相反,我已经渲染了以前的状态我不知道为什么会这样,有人可以解释我的应用程序的行为,并可能提示如何解决它?我甚至不知道在哪里寻找答案。

index.js

import React, { Component } from 'react';
import './App.css';

import { Dropdown } from './components/dropdown'

class App extends Component {

  state = {
      response: "",
      currA: ""
    };

    componentDidMount() {
      this.callApi()
        .then(res => this.setState({ response: res.express }))
        .catch(err => console.log(err));
    }

    callApi = async () => {
      const response = await fetch('/main');
      const body = await response.json();

      if (response.status !== 200) throw Error(body.message);

      return body;
    };

    calculateRate = (currA) => {
      this.setState({currA: currA});
    }

  render() {
    return (
      <div className="App">
        <div>
          <Dropdown callbackFromParent={this.calculateRate}/>
        </div>
        <p>
          {this.state.currA}
        </p>

      </div>
    );
  }
}

export default App;

dropdown.js

import React from 'react';

export class Dropdown extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      list: [],
      selected: ""
    };
  }

componentDidMount(){
  fetch('https://api.fixer.io/latest')
    .then(response => response.json())
    .then(myJson => {
      this.setState({ list: Object.keys(myJson.rates) });
    });
}

change(event) {
  this.setState({ selected: event.target.value });
  this.props.callbackFromParent(this.state.selected);
}

  render(){
    var selectCurr = (curr) =>
     <select
      onChange={this.change.bind(this)}
      value={this.state.currA}
     >
     {(this.state.list).map(x => <option>{x}</option>)}
     </select>;

    return (
      <div>
        {selectCurr()}
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

由于您的setState()不是同步调用,因此可能是您的回调在实际修改下拉列表状态之前触发。您可以尝试在setState上使用回调...

change(event) {
  this.setState({ 
    selected: event.target.value 
  }, () => {this.props.callbackFromParent(event.target.value)});
  ;
}

...或者如果你的父组件是唯一关心所选值的东西(我从你的剪辑中猜到),你根本不需要更新下拉状态。

change(event) {
    this.props.callbackFromParent(event.target.value;)
}
祝你好运!

Documentation:

  

setState()并不总是立即更新组件。它可以批量推迟更新或推迟更新。这使得在调用setState()之后立即读取this.state是一个潜在的陷阱。相反,使用componentDidUpdate或setState回调(setState(更新程序,回调)),其中任何一个都保证在应用更新后触发。如果需要根据以前的状态设置状态,请阅读下面的updater参数。

相关问题