【发布时间】:2020-02-29 20:05:51
【问题描述】:
如何从这个 API 链接 http://www.colr.org/json/color/random 获取随机颜色以及如何使用获取的颜色分别更改列表中的每个元素,例如为 react.js 中的一行列表添加每种颜色?
class FetchRandomColor extends React.Component {
state = {
loading: true,
color: null,
};
async componentDidMount() {
const url = "http://www.colr.org/json/color/random";
const response = await fetch(url);
const data = await response.json();
this.setState({color: data.colors[0]})
}
render() {
return (
<div>
{this.state.loading || !this.state.color ? (
<div>loading...</div>
) : (
<div>
div>{this.state.color}</div>
</div>
)}
</div>
);
} }
渲染(, document.getElementById('root'));
到目前为止,我尝试了这个,但找不到从 api 获取颜色的方法,之后我需要将该颜色应用于列表的每一行
【问题讨论】:
-
到目前为止你有什么尝试?
-
你想做什么?贴一些代码
标签: javascript reactjs api get fetch