React中onAuthStateChange内setState失效、API数据无法渲染卡片问题求助
问题1:点击登录后未跳转到/home路由
根本原因:
- 没有主动触发路由跳转逻辑,
onAuthStateChanged仅更新了user状态,页面仍然停留在/login路由,自然只会渲染Login组件 - 初始state的
user被设为空对象{},空对象的布尔判断结果为true,会导致未登录时访问/home也错误判定为已登录 setState是异步执行的,你在setState后立刻打印this.state.user拿不到更新后的值,属于正常现象,不是setState未生效
修复方案:
- 修改App组件初始state:
this.state={ user : null // 替换原来的{} }
- 在
onAuthStateChanged的登录成功分支添加路由跳转逻辑:
if(User){ this.setState({user: User}) window.location.href = '/home' // 新增跳转逻辑 }
问题2:卡片列表无法正常渲染
根本原因:
- 接口请求成功后,你错误调用了
JSON.stringify(data)把返回的数组转成了字符串,后续slice(0,5)是截取字符串前5位,自然不是你需要的数组数据 itemList函数定义在Home组件外部,无法访问到Home组件的this.staterender中只写了{itemList},没有执行这个函数,且itemList本身也没有把map的结果return出来
修复方案:
- 删除
componentDidMount中多余的JSON序列化步骤:
// 删掉原有.then(data => JSON.stringify(data))步骤,修改为如下逻辑 this.getItems('https://jsonplaceholder.typicode.com/photos') .then( data => { if(this._isMounted) this.setState({items: data.slice(0,5)}) } )
- 把列表渲染逻辑直接写到render方法内,不需要单独定义外部函数:
render(){ return( {/* 省略其他原有代码 */} <Jumbotron> <div className="container"> {this.state.items.map((item) => { return ( <div className="row" key={item.id}> <div className="col-12 col-md-5 m-1"> <Card> <CardImg width="100%" src={item.thumbnailUrl} alt={item.title} /> <CardBody> <CardTitle>{item.title}</CardTitle> <CardText>quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto </CardText> </CardBody> </Card> </div> </div> ); })} </div> </Jumbotron> {/* 省略其他原有代码 */} ) }
内容的提问来源于stack exchange,提问作者Sterlin Peter
相关产品推荐
相关产品推荐

