首页 > 解决方案 > How to refresh a nested Component view that shows the result for a search being done in React

问题描述

I have a dropdown/select for month field and a button which can be clicked to see result for that month.

As in the code below, on clicking the button it sets the query month and changes the ShowResultForMonth component visible.

On click also passes the query month to the component so it renders the result of the nested component correctly. But When i select a new month and click the button again it does not refresh the nested component's view and shows result from the first queried month.

How can we refresh the nested component when i resubmit the selection?

export default class MonthSearch extends Component {
    constructor(props) {
        super(props);
        this.state = {
            queryYear: '',
            months: ['Jan', 'Feb', 'Mar', 'Apr']
            detailVisible: false
        };
    }

    onMonthChange = (event) => {
        this.setState({ queryMonth: event.target.value });
    }

    onSend = (event) => {
        this.setState({ detailVisible: true });
    }

    render() {
        return (
            <div>
                <select onChange={this.onMonthChange}>
                    {this.state.months.map((mt) => <option key={mt.value} value={mt.value}>{mt.display}</option>)}
                </select>
                <button onSubmit={this.onSend}>
                    Search
                </button>
                { this.state.detailVisible ?
                    <ShowResultForTheMonth queryMonth={this.state.queryMonth} />
                    : <h3>select month</h3>
                }
            </div>
        )
    }
}

标签: reactjs

解决方案


a bit fixed your example, it works fine. Take a look, you'll figure out what's wrong with your code

export default class MonthSearch extends Component {
  constructor(props) {
    super(props);
    this.state = {
      queryYear: "",
      months: ["Jan", "Feb", "Mar", "Apr"],
      detailVisible: false
    };
  }

  onMonthChange = (event) => {
    this.setState({ queryMonth: event.target.value });
  };

  onSend = (event) => {
    this.setState({ detailVisible: true });
  };

  render() {
    console.log(this.state)
    return (
      <div>
        <select onChange={this.onMonthChange}>
          {this.state.months.map((mt) => (
            <option key={mt} value={mt}>
              {mt}
            </option>
          ))}
        </select>
        <button onClick={this.onSend}>Search</button>
        {this.state.detailVisible ? (
          <ShowResultForTheMonth queryMonth={this.state.queryMonth} />
        ) : (
          <h3>select month</h3>
        )}
      </div>
    );
  }
}

function ShowResultForTheMonth(props) {
  return (
    <p>{props.queryMonth}</p>
  );
}

推荐阅读