[英]Refresh React Component after changing data from modal dialog box
我正在構建一個小型 Web 應用程序來學習 React,現在遇到了一個問題。 我的任務是單擊特定的城市名稱並轉到將顯示該城市名稱的另一個組件。
在第二個組件上,我有一個模式對話框,我可以在其中更改城市的名稱。 在執行此操作時,我的組件仍然顯示舊城市名稱,而不是我從模式對話框中選擇的新城市名稱。 當我手動刷新頁面時,它確實顯示了新名稱。 我對這些東西的反應和困惑很陌生。 我應該怎么做才能呈現更新的城市名稱?
SecondTable 組件:(我想顯示城市名稱的地方)
class SecondTable extends Component {
state = {
data: [(visible: false), (city: null)]
};
componentDidMount() {
console.log(this.props);
let id = this.props.match.params.city_id;
axios
.get("http://100.124.69.3:8080/api/v1/cities/" + id)
.then(res => {
this.setState({ city: res.data.name });
console.log(res);
});
console.log(this.state.city);
}
render() {
return <div className="align1">{this.state.city}</div>;
}
}
模態對話框的組件,我從中選擇了新城市:
class FacilityModal extends Component {
state = {
cities:[],
}
componentDidMount()
{
console.log(this.props.visa)
await axios.get('http://100.124.68.1:8080/api/v1/cities' ).then(res => {
this.setState({cities:res.data})
});
}
render() {
let posts = (
<div >All Facilities (NCAL)
<div className = 'Modal'>
{this.state.cities.map(city =>
{
return <Link to = {'/'+city.id} key = {city.id} onClick = {this.props.onCancel}> {city.name} </Link>
})}
</div>
</div>
);
return (
<div>
<Modal
title="Change Facility"
visible={this.props.visible}
onCancel={this.props.onCancel}
footer={null}
>
<div>{posts}</div>
</Modal>
</div>
);
}
初始城市列表的 My Home 組件:
class Home extends Component{
state = {
cities:[],
name:''
}
componentDidMount()
{
axios.get('http://100.124.68.1:8080/api/v1/cities').then(res => {
this.setState({cities:res.data})
});
}
render(){
let postList = this.state.cities.map(city =>
{
return (
<div key = {city.id}>
<p>
<Link to = {'/'+city.id}>{city.name}</Link></p>
</div>
)
})
return(
<div className = 'align'>All Facilities (NCAL)
<div class="hr-sect">OR</div>
<div className = 'Modal1'>
{postList}
</div>
</div>
)
}
組件的路由:
render() {
return (
<div >
<BrowserRouter>
<div className="App">
<Header />
<Switch>
<Route exact path='/' component={Home} />
<Route path='/users' component={TableData} />
<Route path='/:city_id' component={SecondTable} />
</Switch>
</div>
</BrowserRouter>
您正在獨立管理每個組件內的狀態。 對您的問題的簡單回答是,您需要更新兩個組件都可以從中呈現的狀態。 您可以通過多種方式實現這一點,從使用像 redux 或 mobx 這樣的狀態管理框架,到使用純粹的反應狀態和重新組織您的組件樹。 如果沒有看到你展示的兩個組件的父組件,很難說你應該怎么做。 它的要點是:將一個函數作為道具傳遞給您的模態組件,該組件將在選擇城市時觸發。 該函數應更新“選定城市”的狀態。 然后,您會將“選定城市”作為道具傳遞給您的 SecondTable 組件。 當狀態更新時,會觸發重新渲染,然后將新的“選定城市”狀態作為道具傳遞給您的 SecondTable 組件,並且它也會使用更新后的值重新渲染。
react 團隊的這篇博文很好地介紹了如何使用 react 解決問題。 我不能推薦它。 https://reactjs.org/docs/thinking-in-react.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.