![](/img/trans.png)
[英]In a react components, how to get latest data from state once it is changed from another component using redux?
[英]How to reload page once state or data is changed within a react class using component did mount
在我的反應應用程序中,我調用了我的路由器,它檢索了我的 mongo db 中的所有動物,然后我根據動物最喜歡的狀態對其進行過濾。 我正在將此數據加載到一個名為動物的列表中,該列表存儲在 class 的 state 中。 我在每只動物的每張卡片上都有一些按鈕,這些按鈕可以更改動物狀態的 state(修改者在反應應用程序中設置,狀態設置為我的快速路線中的收藏夾),並且可能會將它們從動物列表中刪除顯示。 但是,當此 state 像我預期的那樣更改時,此動物列表不會自動更新(一旦將動物更改為收藏,那么我不想在非收藏列表中看到它)。 我不確定如何實現這一點 - 我希望在對動物卡進行更改時重新加載動物列表中的新信息。
我遇到問題的組件的代碼:
export default class AnimalListing extends React.Component {
constructor(props) {
super(props);
this.state = {
animals: null,
update: '',
};
}
starAnimal = async (values) => {
var moddedby = sessionStorage.getItem('username');
const data = {
modified_by: moddedby,
};
fetch(`http://localhost:4000/assign/animal/starred/${values}`, {
method: 'PUT',
body: JSON.stringify(data),
}).then((res) => {
console.log('success');
});
};
componentDidMount() {
axios.get(`http://localhost:4000/animals`, {}).then((animal) => {
this.setState({ animals: animal.data });
});
}
render() {
var Nonfavourite;
Nonfavourite = this.state.tickets
.filter((ticket) => animal.status === 'Non-favourite')
.map((ticket) => (
<div class="card-columns">
<div class="card bg-light">
<div class="card-body text-center">
<h4 class="animal">{animal.name}</h4>
<p>{animal.information}</p>
<p>{animal.status}</p>
<Button
variant="primary"
type="button"
onClick={() => this.starAnimal(animal._id)}
>
Favourite this animal
</Button>
</div>
</div>
</div>
));
return (
<div>
<h4>Animals</h4>
{Nonfavourite}
</div>
);
}
}
快車路線
export const starAnimal = (req, res) => {
var filter = { _id: req.params._id };
var update = {
$set: {
status: 'Favourite',
modified_by: req.body.modified_by,
},
};
Animal.updateOne(filter, update, (err, a) => {
if (err) {
throw err;
} else {
res.status(200).json({
message: 'animal is now a favourite',
});
}
});
};
使 api 在 componentDidMount 中調用一個單獨的 function 像,
const getAnimals = () => {
axios.get(`http://localhost:4000/animals`, {
})
.then((animal)=> {
this.setState({animals: animal.data})
}
}
然后在starAnimal中調用這個function
starAnimal = async values => {
var moddedby = sessionStorage.getItem("username");
const data = {
modified_by: moddedby
}
fetch(`http://localhost:4000/assign/animal/starred/${values}`, {
method:'PUT',
body: JSON.stringify(data)})
}).then(res =>{
console.log("success");
// refetching the animals
this.getAnimals();
})
也在 componentDidMount 中調用它
componentDidMount() {
this.getAnimals();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.