React 中 fetch Promise 链式调用场景下 State 无法更新问题求助
问题根因
- React的状态更新是异步的,调用
setTheID后无法在当前的执行上下文里立刻获取到更新后的theID值 - 本次渲染周期内所有代码读取到的
theID都是闭包捕获的初始值(空字符串),即便你调用了setState,也要等到下次组件重渲染才会拿到新值,你的promise链执行在本次渲染周期内,所以读到的永远是空值。
解决方法
不需要用state来做请求之间的参数传递,直接在promise链中返回需要的参数给下一个环节使用即可,修正后的代码如下:
// 首先提交数据创建管理员账户 fetch('example.com/api/cockpit/saveUser', { method: 'post', headers: { 'Content-Type': 'application/json', 'Cockpit-Token': process.env.REACT_APP_API_KEY }, body: JSON.stringify({ user: { user: firstname.toLowerCase()+surname.toLowerCase(), name: firstname, email: email, password: password, group: 'consumers', } }) }) .then(user => user.json()) .then(()=>{ return fetch(`example.com/api/cockpit/listUsers&filter[email]=${email}`,{ method: 'post', headers: { 'Content-Type': 'application/json', 'Cockpit-Token': process.env.REACT_APP_API_KEY } }) }) .then(res => res.json()) .then(res => { const newUserId = res[0]._id; console.log(newUserId); // 如果后续其他逻辑需要用到这个id存在state里,可以保留set操作 setTheID(newUserId); // 把id传递到下一个promise环节 return newUserId; }) .then(newUserId => { return fetch('example.com/api/collections/save/consumers', { method: 'post', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Cockpit-Token': process.env.REACT_APP_API_KEY, }, body: JSON.stringify({ data: { firstname: firstname, surname: surname, password: password, email: email, project_name: projectName, project_template: tmp, // 直接用上游传递过来的id ass_consumer: newUserId, slug: projectName.toLowerCase().replace(' ','') + '-rr', username: firstname.toLowerCase()+surname.toLowerCase() } }) }) }) .then(user => user.json()) .then(user => { setnewPage(user._id); }) .catch(err => { console.error(err); })
额外优化建议
你可以先核查下saveUser接口的返回值,通常资源创建接口会直接返回新创建资源的完整信息,不需要额外调用listUsers接口查询,可以省去一次不必要的请求开销。
内容的提问来源于stack exchange,提问作者snwmn
相关产品推荐
相关产品推荐

