react根据不同location引入不同的接口要怎么实现

比如一个组件

import {getData,getData1,getData2,...getData10}  from '@/services/demo.ts'
export default const DemoComponent = ()=>{
    // 使用getData,getData1,getData2...
}

现在多个页面使用这一个组件,如何根据不同页面的路径,引入不同的servide,比如另一个页面

import {getData,getData1,getData2,...getData10} from '@/service/demo2.ts'
export default const DemoComponent = ()=>{
    // 使用getData,getData1,getData2...
}

不同页面,只改接口文件的引入,比如只改demo.ts、demo2.t,例如

if(location.path==='demo'){
import {getData,getData1,getData2,...getData10} from '@/service/demo.ts'
}else if(location.path==='demo2'){
import {getData,getData1,getData2,...getData10} from '@/service/demo2.ts'
}
export default const DemoComponent = ()=>{
    // 使用getData,getData1,getData2...
}
阅读 1.9k
1 个回答
新手上路,请多包涵

import from 不能这样引入,es6的import from 引入只能在文件顶部,不能放在逻辑结构里。
你可以一次性都引入,在组件再做逻辑判断,return 不同的组件。
另外,更好的方式是使用 react-router 等路由来实现这个功能。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题