当我尝试console.log时,我的用户列表未定义。 也许我什么都没得到?
我想从可以工作的api(经过邮递员测试)中获取用户列表,然后将其放入控制台,然后我希望映射用户以在应用程序上显示它
class Test extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
}
}
componentDidMount() {
console.log("component did mount");
fetch("/user/list")
.then(res => {
return res.json();
})
.then(users =>
this.setState({users}, () =>
console.log("list of users => " + users)));
}
render() {
return (
<div className="form">
<ul>
{this.state.users.map((user) =>
<li key="user._id">{ user.name }</li>
)}
</ul>
</div>
);
}
} export default Test;
感谢帮助!
答案 0 :(得分:1)
您必须返回res.json()
才能在下一个.then()
.then(res => {
res.json();
})
应该是
.then(res =>
res.json();
)
或
.then(res => {
return res.json();
})
答案 1 :(得分:1)
您正在调用res.json()
,而不是从提取调用的第一个res.json()
返回then
我发现这种模式很有帮助:
fetch(url)
.then(res => res.ok ? res.json() : Promise.reject())
就像现在的代码一样,users
(第二个then
中的参数是未定义的,因为您没有从第一个then
返回任何内容
答案 2 :(得分:0)
您应该将res传递到res.json()并将结果返回到您的状态。
componentDidMount() {
console.log("component did mount");
fetch("/user/list")
.then(res => res.json())
.then(users =>
this.setState(users,
() => {
console.log("list of users => " + users)
})
);
}
答案 3 :(得分:0)
Michael Jasper的回复对我有很大帮助!
我发现,如果我们传递任何请求正文,则使用GET方法进行提取是行不通的。
完整的示例在这里 https://github.com/alexunjm/todo-list-react
const buildRequestOptions = ({
method = "GET",
raw = null, // I had my error here!, with GET raw need to be null
customHeaders = {name: 'value'},
}) => {
var myHeaders = buildHeaders(customHeaders);
var requestOptions = {
method,
headers: myHeaders,
body: raw,
redirect: "follow",
};
return requestOptions;
};
const listTasks = () => {
const url = `${uriBase}/task/sample`;
const requestOptions = buildRequestOptions({
customHeaders: { "Content-Type": "application/json" },
});
return fetch(url, requestOptions);
}
const asyncFn = ({
promiseToWait,
pendingFn,
successFn,
errorFn,
}) => {
return (dispatch) => {
dispatch(pendingFn());
promiseToWait
.then((res) => {
if (res.ok) {
return res.json();
}
// handled from server status 422 and 401
if (res.status === 422) {
// error message on body from server
return res.json();
}
if (res.status === 401) {
// custom error message hardcoded
return {errors: {action: 'no authorized'}}
}
console.log("http response no controlled", res);
return Promise.reject();
})
.then((body) => {
if (body.errors) {
const errors = Object.keys(body.errors).map(
(key) => key + " " + body.errors[key]
);
dispatch(errorFn(errors.join("; ")));
} else {
dispatch(successFn(body));
}
return body;
})
.catch((error) => {
console.log("error", error);
dispatch(errorFn("Unavailable server connection"));
});
};
};
const queryTasks = () => {
return asyncFn({
promiseToWait: listTasks(),
pendingFn: apiPending,
successFn: apiSuccessList,
errorFn: apiError,
});
}