[英]ReactJS can not rerender Component by onClick
我用react.js制作簡單的應用程序,每次點擊按鈕時建議隨機放置按鈕,一次單擊后問題無法重新渲染組件每次點擊按鈕我怎樣才能獲得新的位置
place.js用於獲取數據的獲取API
state = { loading: true, person: null };
async componentDidMount() {
let Xyurl = "https://cors-anywhere.herokuapp.com/";
let url =
"https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g et_param=value";
let response = await fetch(Xyurl + url);
let data = await response.json();
this.setState({ place: data, loading: false });
}
render() {
return (
<div>
<div>
{this.state.loading || !this.state.place ? (
<div>loading......</div>
) : (
<div className="PlcseContiner">
<img alt="description" src= .
{this.state.place.image[0]} />
{this.state.place.name}
</div>
</div>
);
建議從按鈕可以呈現位置的位置
class Suggestion extends Component {
constructor(props) {
super(props);
this.state = {
visible: false
};
this.handleClicked = this.handleClicked.bind(this);
}
handleClicked(event) {
event.preventDefault();
this.setState({
visible: true
});
}
generateplace() {
if (this.state.visible) {
return <Place />;
}
return null;
}
render() {
return (
<div className="main-button">
<Button onClick={this.handleClicked} color="warning" className="Btn">
suggestion
</Button>
{this.generateplace()}
</div>
);
}
}
您可以使用componentWillUpdate
從父級控制它,因此您需要向Place
組件添加道具
建議:
class Suggestion extends Component {
constructor(props) {
super(props);
this.state = {
visible: false,
refresh: 1
};
this.handleClicked = this.handleClicked.bind(this);
}
handleClicked(event) {
event.preventDefault();
this.setState({
visible: true,
refresh: this.state.refresh + 1
});
}
generateplace() {
if (this.state.visible) {
return <Place refresh={this.state.refresh} />;
}
return null;
}
render() {
return (
<div className="main-button">
<Button onClick={this.handleClicked} color="warning" className="Btn">
suggestion
</Button>
{this.generateplace()}
</div>
);
}
您需要將操作分隔為以下函數:
地點:
componentDidMount() {
this.getPlace()
}
componentWillUpdate(nextProps, nextState) {
this.getPlace();
}
getPlace = async() => {
let Xyurl = "https://cors-anywhere.herokuapp.com/";
let url =
"https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g et_param=value";
let response = await fetch(Xyurl + url);
let data = await response.json();
this.setState({ place: data, loading: false });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.