React中如何从其他组件获取API返回的字符串并做条件判断?
核心问题误区
你当前写的判断逻辑永远不会触发预期效果,几个核心问题导致拿不到正确值:
- 写出的
const recommended = <UserList></UserList>,本质是React生成的虚拟DOM对象,不是组件最终渲染在页面上的"Rome"文本,直接拿这个对象和字符串做相等判断,结果永远是false - UserList内部发起的是异步接口请求,返回值只存在于组件自身的作用域中,外层组件无法直接通过引用JSX元素读取到这个异步返回的业务数据
- 现有判断分支的匹配值写的是
"Roam in Rome",但接口实际返回的是字符串"Rome",就算拿到了正确值,这个判断条件也匹配不上
最适配React设计的实现方案:状态提升
把之前写在UserList内部的接口请求、状态存储逻辑,统一上移到上层的App组件中,让上层组件直接持有接口返回的推荐值,从根源上解决“跨组件读渲染文本”的反模式问题。
- 把UserList改造为纯展示组件,不再自带请求和状态,只通过props接收要展示的推荐数据:
// 改造后的UserList:仅负责展示传入的推荐列表 const UserList = ({ recommendations }) => { const customers = recommendations.map((item, index) => ( <div key={index}> <h1>{item}</h1> </div> )); return ( <div id="layout-content" className="layout-content-wrapper"> <div className="panel-list">{customers}</div> </div> ); }; - 在App组件中接管原本的请求逻辑,拿到返回值后直接在当前作用域完成条件判断:
class App extends React.Component { constructor(props) { super(props); this.state = { predictionList: [], requestError: false }; } componentDidMount() { fetch('https://surpriserecommenderapi.herokuapp.com/recommend?customer_id=alakbar@gmail.com', { method: "post", headers: { "Content-Type": "application/json" } }).then(response => { if (!response.ok) { throw new Error(`HTTP error ${response.status}`); } return response.json(); }) .then(({ prediction }) => { // 此处直接拿到接口返回的推荐值,完全可以在当前作用域做条件校验 this.setState({ predictionList: prediction }); }) .catch(error => { this.setState({ requestError: true }); }); } render() { // 从状态中取出推荐目的地,做条件判断 const recommendedDestination = this.state.predictionList[0]?.trim(); let recommendedPackage; if (recommendedDestination === "Rome") { recommendedPackage = <div>Recommended package: Roam in Rome</div> } else { recommendedPackage = <div>No recommended package</div> } return ( <div className="app-root"> {/* 渲染原有的UserList组件,把拿到的推荐值作为props传入 */} <UserList recommendations={this.state.predictionList} /> {/* 渲染条件判断后生成的推荐包内容 */} {recommendedPackage} </div> ); } }
可选兼容方案:组件结果回传
如果不想改动原有UserList独立发请求的逻辑,可以给UserList新增一个回调类型的props,让组件在拿到接口返回值时,主动把数据传递给上层组件,不需要从DOM中提取文本。
- 给原有UserList新增回调逻辑,拿到结果后同步回传给上层:
// UserList内部调整的部分 .then(({ prediction }) => { this.setState({ customer: prediction }); // 拿到结果后调用上层传入的回调,把数据传出去 this.props.onReceiveResult?.(prediction); }) - 上层App组件传入回调函数,接住回传的结果后做判断:
class App extends React.Component { state = { recommendedList: [] } // 接住UserList回传的推荐结果 handleReceiveResult = (prediction) => { this.setState({ recommendedList: prediction }, () => { // 状态更新完成后,就可以直接做需要的if判断 if (prediction[0] === "Rome") { console.log("匹配到罗马线路的推荐包"); } }) } render() { return ( <div> <UserList onReceiveResult={this.handleReceiveResult} /> </div> ) } }
内容的提问来源于stack exchange,提问作者ajnabz
相关产品推荐
相关产品推荐

