我正在使用react useParams
钩子来获取URL参数id。在组件 AppMessageItems 中,我获得了ID,但是如何将这些数据发送到 getMessages 函数以发送到端点。但是,当我尝试在 getMessages 函数中获取参数id时,会给出有关使用钩子无效的错误
const AppMessageItems = ( {messages, getMessages} ) => {
let { id } = useParams();
console.log(id) // 123
useEffect( () => {
const setUserMessageDataToLocalStorage = localStorage.getItem('token');
getMessages(setUserMessageDataToLocalStorage)
}, []);
return (
<Container>
<TabPanelContainer>
<TabPanelHeader/>
<TabPanelBody />
<TabPanelFooter/>
</TabPanelContainer>
</Container>
)
};
const getMessages = (token) => async (dispatch) => {
// test data
const all = {
pass: 'Hello World',
};
try {
const getMessages = await axios.post(API.getUserMessages, {}, {headers: {"Authorization": 'Bearer ' + token}})
.then(res => res.data);
dispatch(getMessagesDispatch(all));
} catch (err) {
console.log("Error GET_MESSAGES");
}
};
答案 0 :(得分:0)
我评论过。这是演练:
const AppMessageItems = ( {messages, getMessages} ) => {
let { id } = useParams();
const dispatch = useDispatch();
console.log(id) // 123
useEffect( () => {
const setUserMessageDataToLocalStorage = localStorage.getItem('token');
dispatch(getMessages(setUserMessageDataToLocalStorage, id))
}, [id, dispatch]);
return (
<Container>
<TabPanelContainer>
<TabPanelHeader/>
<TabPanelBody />
<TabPanelFooter/>
</TabPanelContainer>
</Container>
)
};
const getMessages = (token, id) => async (dispatch) => {
// use the id param whereever
// test data
const all = {
pass: 'Hello World',
};
try {
const {data} = await axios.post(API.getUserMessages, {}, {headers: {"Authorization": 'Bearer ' + token}})
dispatch(getMessagesDispatch(all));
} catch (err) {
console.log("Error GET_MESSAGES");
}
};