【发布时间】:2017-10-05 13:18:32
【问题描述】:
我正在开发一个 ReactJS 项目,您可以在按下生成按钮时生成随机活动。我正在获取我的 api 以显示其中的一些数据。这工作正常。现在我想每次单击生成按钮(位于主组件中)时都进行获取并显示返回的数据。因此生成按钮必须执行新的获取并刷新组件。默认情况下它必须为空。我搜索了一段时间,找不到相关的答案。你们中的一些人可以帮助我吗?谢谢。
获取组件
import React from "react";
export class ItemLister extends React.Component {
constructor() {
super();
this.state = { suggestion: "" };
}
componentDidMount() {
fetch("......./suggestions/random", {
method: "GET",
dataType: "JSON",
headers: {
"Content-Type": "application/json; charset=utf-8"
}
})
.then(resp => {
return resp.json();
})
.then(data => {
this.setState({ suggestion: data.suggestion });
})
.catch(error => {
console.log(error, "catch the hoop");
});
}
render() {
return <h2>{this.state.suggestion}</h2>;
}
}
主页组件
import React from "react";
import { ItemLister } from "./apiCall";
export class Home extends React.Component {
constructor(props) {
super(props);
console.log();
window.sessionStorage.setItem("name", this.props.params.name);
window.sessionStorage.setItem("token", this.props.params.token);
}
render() {
return (
<div className="contentContainer AD">
<table>
<thead>
<tr>
<th>
<p>Het is heel leuk als het werkt!</p>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<ItemLister />
</td>
</tr>
</tbody>
</table>
<div className="container center">
<button>GENERATE</button>
<button>SAVE</button>
<button>MATCH</button>
</div>
</div>
);
}
}
【问题讨论】:
-
您是否仍然面临渲染建议的任何问题?
-
不,不带渲染。主要问题是在生成按钮中设置一个 onClick 以连接 fetch 功能。
-
您希望每次通过单击生成按钮来刷新 ItemListener 组件。对吗?
-
没错