React API调用中useParams的id未替换及slice传参问题
控制台打印显示模板字符串
${id}未替换的原因 这个现象不是代码bug,是你打印的内容不对:
- 你执行
console.log(api)时,打印的是api这个异步函数的源码文本,不是函数执行后的运行结果。 - 模板字符串的插值计算只会发生在函数实际执行的阶段,你没有调用
api()的时候,JS不会去解析${id}的实际值,控制台输出的源码里自然会保留${id}的原始写法。 - 验证方式:在
api函数内部、发起axios请求前加打印逻辑,再调用api(),就能看到拼接完成的真实请求地址:
const api = async () => { try { const requestUrl = `http://127.0.0.1:8000/api/maintenance/${id}` console.log('实际请求地址:', requestUrl) // 这里打印才会看到替换后的值 const res = await axios.get(requestUrl); return res.data; } catch (error) { console.log(error); } };
另外你当前代码还有个逻辑问题:useEffect里调用的是fetchComponents(),既没有使用你定义的api函数,也没有把路由拿到的id传入请求逻辑,后续就算请求能发出去也拿不到对应id的数据。
将API请求移到Redux Slice时传递动态id的实现方式
最直接的做法是在dispatch异步action的时候,把id作为参数传入,不需要额外把id存到Redux状态里,两种常用写法如下:
1. 使用Redux Toolkit的createAsyncThunk
组件侧调用时传入id:
useEffect(() => { // dispatch时把路由拿到的id作为参数传入 dispatch(fetchComponents(id)) }, [dispatch, id]); // 必须把id加入依赖数组,id变化时自动重新拉取数据
Slice侧的thunk定义里直接接收参数:
export const fetchComponents = createAsyncThunk( 'components/fetchComponents', // 第一个入参就是dispatch时传过来的id async (id) => { const res = await axios.get(`http://127.0.0.1:8000/api/maintenance/${id}`); return res.data; } ) // 后续在extraReducers里处理pending/fulfilled/rejected状态即可
2. 手写原生Redux thunk
thunk定义时外层函数接收id,内层异步函数直接使用:
// thunk定义 export const fetchComponents = (id) => async (dispatch) => { dispatch({ type: 'components/fetchPending' }) try { const res = await axios.get(`http://127.0.0.1:8000/api/maintenance/${id}`); dispatch({ type: 'components/fetchSuccess', payload: res.data }) } catch (error) { dispatch({ type: 'components/fetchFail', payload: error }) } }
组件侧调用方式和上面一致,dispatch时传入id即可。
内容的提问来源于stack exchange,提问作者newprogrammer12
相关产品推荐
相关产品推荐

