reactjs - 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>
)
}
}
解决方案
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>
);
}
推荐阅读
- python - 连接两行 CSV 文件
- tensorflow - 使用 tensorflow 在 GPU 上进行 OOM,同时制作 Mandelbrot
- c++ - CLI 与来自 C++ 程序的 API 调用
- java - LinkedHashSet vs HashSet - 迭代性能取决于对象类型?
- node.js - 沃尔玛 MWS API 未返回 nextCursor
- python - 尝试抓取单个网站页面时出现 503 错误 | 蟒蛇 | 要求
- android-studio - 无法在 LiveData Observer 内的 MutableList 中添加项目
- python - 尽管 pandas 旧版本,文件不是 zip 文件错误
- python - 如何每 n 行获取 np.arrays 列的平均值,然后将平均值添加到组中每个成员的新列
- java - 验证文件是否存在于特定的 ftp 服务器位置