我是 React 新手,并开始考虑拉入 json 数据。 为了测试我正在使用:https://randomuser.me/api/?results=5
我想要实现的是,当我单击 json 中的用户名时,它将控制台记录用户名。如何将值从 json 传递到控制台日志?
const API = 'https://randomuser.me/api/?results=5';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
logins: [],
};
}
componentDidMount() {
fetch(API)
.then(response => response.json())
.then(data => {
let logins = data.results.map((uname) => {
return (
<div>
<button>{uname.login.username}</button>
</div>
)
})
this.setState({logins: logins});
})
}
render() {
return (
<div>
{this.state.logins}
</div>
);
}
}
在 componentDidMount 中返回 html 代码是个好主意还是应该让它继续渲染?
最佳答案
您可以做您喜欢做的事情,但通常您会将组件创建(它不是真正的 HTML)留给渲染
:
const API = 'https://randomuser.me/api/?results=5';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
logins: [],
};
}
componentDidMount() {
fetch(API)
.then(response => response.json())
.then(data => {
this.setState({logins: data.results});
})
}
render() {
return (
<div>
{this.state.logins.map((uname) => (
<div>
<button>{uname.login.username}</button>
</div>
))}
</div>
);
}
}
state
通常应保存数据,并将该数据的渲染留给render
。
旁注:您的 fetch
调用缺少两件事:
检查
ok
状态,以及错误处理程序
fetch(API) .then(response => { // *** if (!response.ok) { // *** throw new Error({status: response.status}); // *** } // *** }) // *** .then(response => response.json()) .then(data => { // ... }) .catch(err => { // *** // Handle the error // *** }); // ***
fetch
不会拒绝 404 等状态错误。
关于javascript - React json 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50024611/