Javascript 财产';长度';未定义-反应教程
我正在遵循react教程,但有一个错误不允许我继续,我尝试了所有方法,但什么都没有尝试,它给出了未定义的结果,但我已经更改了一些内容,无法解决 代码:Javascript 财产';长度';未定义-反应教程,javascript,reactjs,react-native,okta,Javascript,Reactjs,React Native,Okta,我正在遵循react教程,但有一个错误不允许我继续,我尝试了所有方法,但什么都没有尝试,它给出了未定义的结果,但我已经更改了一些内容,无法解决 代码: class PostsManager extends Component { state = { loading: true, posts: [], }; componentDidMount() { this.getPosts(); } async fetch(method, endpoint,
class PostsManager extends Component {
state = {
loading: true,
posts: [],
};
componentDidMount() {
this.getPosts();
}
async fetch(method, endpoint, body) {
try {
const response = await fetch(`${API}${endpoint}`, {
method,
body: body && JSON.stringify(body),
headers: {
'content-type': 'application/json',
accept: 'application/json',
authorization: `Bearer ${await this.props.auth.getAccessToken()}`,
},
});
return await response.json();
} catch (error) {
console.error(error);
}
}
async getPosts() {
this.setState({ loading: false, posts: await this.fetch('get', '/posts') });
}
async deletePost(post) {
if (window.confirm(`Are you sure you want to delete "${post.title}"`)) {
await this.fetch('delete', `/posts/${post.id}`);
this.getPosts();
}
}
return (
<Fragment>
<Typography variant="display1">Posts Manager</Typography>
{this.state.posts.length > 0 ? (
<Paper elevation={1} className={classes.posts}>
<List>
....
类PostsManager扩展组件{
状态={
加载:对,
员额:[],
};
componentDidMount(){
这是getPosts();
}
异步获取(方法、端点、主体){
试一试{
const response=await fetch(`${API}${endpoint}`{
方法
body:body&&JSON.stringify(body),
标题:{
“内容类型”:“应用程序/json”,
接受:'application/json',
授权:`Bearer${wait this.props.auth.getAccessToken()}`,
},
});
return wait response.json();
}捕获(错误){
控制台错误(error);
}
}
异步getPosts(){
this.setState({loading:false,posts:wait this.fetch('get','/posts'))});
}
异步删除post(post){
if(window.confirm(`是否确实要删除“${post.title}”`)){
等待这个.fetch('delete',`/posts/${post.id}`);
这是getPosts();
}
}
返回(
邮政经理
{this.state.posts.length>0(
....
假设this.fetch('get','/posts')
工作并返回一些json,您需要实际评估响应:
async getPosts() {
const response = await this.fetch('get', '/posts');
const json = await response.json();
this.setState({ loading: false, posts: json });
}
有关mdn的详细信息。您希望呈现…
,但出现错误。这是因为此.state.posts
为空/未定义,并且不能在此类文件上使用长度
解决方案:创建一个if条件并等待它不再为null
if(this.state.posts!=null){
回报率(…);
}
否则{
返回(正在加载…;//或其他内容
}
您的Glup3同意Glup3,但我只会使用
this.state.posts.length
而不是检查长度是否大于0。这样,如果.length未定义或为0,它将是错误的
{this.state.posts.length ? ....
你的报税表似乎没有办法。请给出一个答案。