React Native中如何从Helper函数调度Redux Action并获取Store Token
Your issue comes down to this: your helper.js file doesn’t have direct access to the Redux store’s dispatch method or state. When you called helloWorld() directly, it only returned the thunk function but didn’t execute it with the necessary dispatch argument. Here’s how to fix this step by step:
Step 1: Export Your Redux Store Instance
First, make sure your Redux store is exported from the file where it’s created (typically store.js):
// store.js import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers'; // Create store with thunk middleware (required for async actions) const store = createStore(rootReducer, applyMiddleware(thunk)); export default store;
Step 2: Import the Store in helper.js
Now you can import the store into your helper file to access state and dispatch actions:
// helper.js import store from './store'; // Adjust path to match your project structure import axios from 'axios'; import Toast from 'your-toast-library'; // Replace with your actual toast library import import { helloWorld, logoutAction } from './actions'; // Import your action creators
Step 3: Fetch Token from Redux Store (Instead of Parameter)
Modify your HTTPRequest function to get the user token directly from the store, no need to pass it as a parameter:
const HTTPRequest = (path, body, method = 'POST') => { return new Promise((resolve, reject) => { let headers = { 'Content-type': 'multipart/form-data', }; // Get token from Redux state (adjust the path to match your actual state structure) const currentState = store.getState(); const authorizedToken = currentState.user?.token; if (authorizedToken) { headers['Authorization'] = "JWT " + authorizedToken; } // Fix: Add `data: body` to axios config (you were missing this critical piece!) const fulHeaderBody = { method, headers, timeout: 20000, // Note: Timeout is in milliseconds (20ms was way too short!) url: path, data: body }; axios(fulHeaderBody).then(response => { if (response.success) { resolve(response); } else { Toast.show({ text: response.message ? response.message : 'Something went wrong.', buttonText: 'Okay', type: 'danger' }); resolve(response); } }).catch(error => { if (error.response) { if(error.response.status === 401){ // Dispatch logout action using the store store.dispatch(logoutAction()); }else{ console.log('Error', error.message); } } else { console.log('Error', error.message); } console.log(error.config); reject(error); }) }); }; export default HTTPRequest;
Step 4: Dispatch Actions Correctly
To fix your helloWorld action issue, dispatch it using the store’s dispatch method instead of calling the action creator directly:
// Inside helper.js (wherever you want to trigger the action) store.dispatch(helloWorld());
Why This Works:
store.getState()gives you a snapshot of the current Redux state, so you can access the user’s token without passing it around as a parameter.store.dispatch()triggers Redux’s middleware (like thunk) to execute your action creators. For thunk actions, the middleware automatically injects thedispatchandgetStatearguments—this is why your original call tohelloWorld()didn’t work; it was missing this injection.
Key Fixes to Note:
- Timeout Value: Your original timeout was set to
20milliseconds, which is far too short. I changed it to20000(20 seconds) to avoid unnecessary failed requests. - Request Body: You forgot to include
data: bodyin your axios config, which meant your POST requests weren’t sending any body data. This is now added to ensure your requests work as intended.
内容的提问来源于stack exchange,提问作者user7747472

