javascript - ReactJS 无法通过 onClick 重新渲染组件
问题描述
我用 react.js 制作了一个简单的应用程序,每次单击按钮时建议随机放置 问题无法在单击后重新渲染组件 每次单击按钮时如何获取新位置
place.js where fetch 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 });
}
推荐阅读
- unity3d - 如何在Unity中制作区域高度雾,例如森林区域有雾,道路区域没有
- regex - 仅允许此正则表达式中的单个点
- android - 调用网络服务的最佳方式?
- java - 在 Spring Boot 应用程序上添加动态属性
- java - Java 赋值运算符在 lambda 表达式中返回值
- eclipse - eclipse git如何与远程存储库包资源管理器同步本地分支
- android - LinearLayout 将 textview 水平对齐到 linearlayout 垂直方向内的按钮中心
- rest - 以更好的方式在获取请求中返回对象属性
- magento-1.9 - 折扣价格消失一段时间
- javascript - 使用 JavaScript 在移动浏览器虚拟键盘中自定义 Enter 键