【发布时间】:2018-07-18 10:56:51
【问题描述】:
我正在尝试调用 API 以在 React.js 中在我的网站上显示信息,API 需要读取令牌,但我不知道我必须做什么才能生成令牌,因为我的应用程序不需要任何注册或登录。它就像一个产品目录,您可以对其进行个性化设置。我不太了解这个,因为我是新手,我是自学,所以很抱歉,如果这令人困惑,请随时提出任何问题,我会尽力回答:)
这是我到现在为止的代码:
export class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
models: [],
isLoaded: false
};
}
componentDidMount() {
fetch(myUrlAPI)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
models: json
});
});
}
render() {
const { isLoaded, models } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>
<ul>{models.map(model => <li>{model.name}</li>)};</ul>
<a href="/sofa">
<div className="Parcelas">
<img
src="../../img/image-card-1@2x.png"
className="ParcImage"
alt="sofa"
/>
<h1>Sofa hipnos</h1>
<h2>
1,200<span>€</span>
</h2>
<p className="Features">
w 20.5 x 15.5 x h 19.5 (cm)<br />Pele
</p>
<button className="Botao">
<p className="MostraDepois">See Details</p>
<span>+</span>
</button>
<img
src="../../img/points.svg"
className="Decoration"
alt="points"
/>
</div>
</a>
</div>
);
}
}
}
在 <ul> 标签中,我只是想测试 json 的结果。
另外,每次我使用.map 制作数组时,都会收到此错误(TypeError: models.map is not a function)或类似错误,您能告诉我为什么吗?
【问题讨论】:
-
models最初是您所在州的一个数组,所以我猜想您在获取完成时设置为models的json很可能不是一个数组。你能在setState之前做console.log(json);看看数据是什么样的吗?needs a token to be read很难为您提供帮助,因为您还没有告诉我们您使用的是什么 API。 -
console.log(json) 返回了这个:
{detail: "Authentication credentials were not provided."}@Tholle -
好的。将您的阵列设置为此将不起作用。您可能想在第一个
then回调中执行一些额外的逻辑,例如then(res => { if (!response.ok) { throw Error(response.statusText); } else { return res.json(); } })并在您的承诺链末尾添加catch,例如.catch(error => console.error(error)) -
返回相同的消息,没有别的...
-
您使用的是什么 API?
标签: javascript reactjs rest api react-native