반응 컴포넌트 외부에 있는 레덕스 스토어에 액세스하는 가장 좋은 방법은 무엇입니까?
@connect리액션 컴포넌트 내의 스토어에 접속하려고 할 때 매우 효과적입니다.하지만 다른 코드로 접속하려면 어떻게 해야 하죠?예: 앱에서 글로벌하게 사용할 수 있는 Axios 인스턴스를 만들기 위해 인증 토큰을 사용한다고 가정해 보겠습니다.그것을 실현하는 가장 좋은 방법은 무엇일까요?
이건 내 거야api.js
// tooling modules
import axios from 'axios'
// configuration
const api = axios.create()
api.defaults.baseURL = 'http://localhost:5001/api/v1'
api.defaults.headers.common['Authorization'] = 'AUTH_TOKEN' // need the token here
api.defaults.headers.post['Content-Type'] = 'application/json'
export default api
이제 스토어에서 데이터 포인트에 액세스하려고 합니다.리액션 컴포넌트 내에서 데이터 포인트를 가져오려고 하면 다음과 같이 됩니다.@connect
// connect to store
@connect((store) => {
return {
auth: store.auth
}
})
export default class App extends Component {
componentWillMount() {
// this is how I would get it in my react component
console.log(this.props.auth.tokens.authorization_token)
}
render() {...}
}
통찰력이나 워크플로우 패턴 같은 건 없나요?
호출한 모듈에서 스토어를 내보냅니다.createStore그러면 글로벌 윈도우 공간이 생성되고 오염되지 않을 것입니다.
MyStore.js
const store = createStore(myReducer);
export store;
또는
const store = createStore(myReducer);
export default store;
MyClient.js
import {store} from './MyStore'
store.dispatch(...)
또는 디폴트를 사용한 경우
import store from './MyStore'
store.dispatch(...)
여러 스토어 사용 사례
스토어의 인스턴스가 여러 개 필요한 경우 공장 함수를 내보냅니다.만드는 것을 추천합니다.async(예:promise).
async function getUserStore (userId) {
// check if user store exists and return or create it.
}
export getUserStore
클라이언트 상(내)async블록)
import {getUserStore} from './store'
const joeStore = await getUserStore('joe')
해결책을 찾았습니다.그래서 저는 api util에 스토어를 Import하여 그곳에서 구독합니다.그리고 그 청취자 기능에서는 새로 가져온 토큰으로 액시오스의 글로벌 디폴트를 설정합니다.
이것이 나의 새로운 것이다.api.js외관:
// tooling modules
import axios from 'axios'
// store
import store from '../store'
store.subscribe(listener)
function select(state) {
return state.auth.tokens.authentication_token
}
function listener() {
let token = select(store.getState())
axios.defaults.headers.common['Authorization'] = token;
}
// configuration
const api = axios.create({
baseURL: 'http://localhost:5001/api/v1',
headers: {
'Content-Type': 'application/json',
}
})
export default api
아마 좀 더 개선될 수 있을 것 같은데, 지금은 좀 품위 없어 보이니까.나중에 할 수 있는 것은 미들웨어를 가게에 추가하고 토큰을 설정하는 것입니다.
사용할 수 있습니다.store반환되는 오브젝트createStore함수(앱 초기화 시 코드에서 이미 사용되어야 함)이 개체를 사용하여 현재 상태를 가져올 수 있습니다.store.getState()메서드 또는store.subscribe(listener)스토어 업데이트를 구독합니다.
이 오브젝트를 저장할 수도 있습니다.window필요에 따라서, 애플리케이션의 어느 부분으로부터도 액세스 할 수 있는 속성).window.store = store)
상세한 것에 대하여는, 「Redux」를 참조해 주세요.
사용할 수 있습니다.Middleware비반응 컴포넌트 스토어에 접속하는 방법:
미들웨어
function myServiceMiddleware(myService) {
return ({ dispatch, getState }) => next => action => {
if (action.type == 'SOMETHING_SPECIAL') {
myService.doSomething(getState());
myService.doSomethingElse().then(result => dispatch({ type: 'SOMETHING_ELSE', result }))
}
return next(action);
}
}
사용.
import { createStore, applyMiddleware } from 'redux'
const serviceMiddleware = myServiceMiddleware(myService)
const store = createStore(reducer, applyMiddleware(serviceMiddleware))
@sanchit에서 제안하는 미들웨어와 마찬가지로 이미 Axios 인스턴스를 글로벌하게 정의하고 있다면 좋은 솔루션입니다.
다음과 같은 미들웨어를 만들 수 있습니다.
function createAxiosAuthMiddleware() {
return ({ getState }) => next => (action) => {
const { token } = getState().authentication;
global.axios.defaults.headers.common.Authorization = token ? `Bearer ${token}` : null;
return next(action);
};
}
const axiosAuth = createAxiosAuthMiddleware();
export default axiosAuth;
그리고 이렇게 사용하세요.
import { createStore, applyMiddleware } from 'redux';
const store = createStore(reducer, applyMiddleware(axiosAuth))
모든 액션에 토큰이 설정되지만 예를 들어 토큰을 변경하는 액션만 수신할 수 있습니다.
조금 늦을 수도 있지만, 가장 좋은 방법은 이 제품을 사용하는 것입니다.axios.interceptors하와같같 같같같다다Import URL 입니다.
index.displaces를 표시합니다.
import axios from 'axios';
import setupAxios from './redux/setupAxios';
import store from './redux/store';
// some other codes
setupAxios(axios, store);
셋업 Axios.js
export default function setupAxios(axios, store) {
axios.interceptors.request.use(
(config) => {
const {
auth: { tokens: { authorization_token } },
} = store.getState();
if (authorization_token) {
config.headers.Authorization = `Bearer ${authorization_token}`;
}
return config;
},
(err) => Promise.reject(err)
);
}
갈고리로 하는 거.비슷한 문제에 부딪혔는데, 후크가 달린 리액트 리덕스를 사용하고 있었어요.인터페이스 코드(즉, 리액트 컴포넌트)를 스토어에서 정보를 취득/송신하기 위한 전용 코드로 가득 채우고 싶지 않았습니다.그보다는 일반적인 이름을 가진 기능들이 데이터를 검색하고 업데이트하기를 원했습니다.내 길은 앱의 기능을
const store = createSore(
allReducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
로 합니다.store.js "" 추가export 전에constfilestore.합니다. react-displayx Import를 선택합니다.나서 저는 수입하다로 수입했습니다.index.jsindex.를 통상적인 .js Import는 index.js로 Import합니다.import {store} from "./store.js" 아이 는 '아이다'를 사용하여 가게에 .useSelector() ★★★★★★★★★★★★★★★★★」useDispatch()
코드로 한 Import Import)를했습니다.import {store} from "../../store.js"를 사용하고 나서, 「」를 사용합니다.store.getState() ★★★★★★★★★★★★★★★★★」store.dispatch({*action goes here*})저장소 검색 및 업데이트(또는 작업 전송)를 처리합니다.
TypeScript 2.0의 경우 다음과 같습니다.
MyStore.ts
export namespace Store {
export type Login = { isLoggedIn: boolean }
export type All = {
login: Login
}
}
import { reducers } from '../Reducers'
import * as Redux from 'redux'
const reduxStore: Redux.Store<Store.All> = Redux.createStore(reducers)
export default reduxStore;
MyClient.tsx
import reduxStore from "../Store";
{reduxStore.dispatch(...)}
내 저장소 변수 내보내기
내보내기 const store = createStore(rootReducer, applyMiddleware(ReduxThunk));
이 파일을 Import해야 합니다(스토어).
".path..."에서 {store} 가져오기";
이 단계는 함수가 있는 저장 변수에서 sate를 가져옵니다.
const state = store.getState();
모든 주의 앱을 이용할 수 있습니다.
토큰에 쉽게 액세스할 수 있는 방법은 토큰을 LocalStorage 또는 React Native를 사용하여 AsyncStorage에 넣는 것입니다.
React Native 프로젝트의 다음 예
authReducer.js
import { AsyncStorage } from 'react-native';
...
const auth = (state = initialState, action) => {
switch (action.type) {
case SUCCESS_LOGIN:
AsyncStorage.setItem('token', action.payload.token);
return {
...state,
...action.payload,
};
case REQUEST_LOGOUT:
AsyncStorage.removeItem('token');
return {};
default:
return state;
}
};
...
★★★★★★★★★★★★★★★★★」api.js
import axios from 'axios';
import { AsyncStorage } from 'react-native';
const defaultHeaders = {
'Content-Type': 'application/json',
};
const config = {
...
};
const request = axios.create(config);
const protectedRequest = options => {
return AsyncStorage.getItem('token').then(token => {
if (token) {
return request({
headers: {
...defaultHeaders,
Authorization: `Bearer ${token}`,
},
...options,
});
}
return new Error('NO_TOKEN_SET');
});
};
export { request, protectedRequest };
의 는, 「」를 사용할 수 .Window.localStorage
저도 같은 문제에 직면했습니다.React 내 어디에서나 액세스 할 수 있는 글로벌 Axios 설정을 하고 싶었습니다(컴포넌트, 컴포넌트 외, thunk 액션 내).
설정 오브젝트를 반환하는 트렁크를 쓰게 되었습니다.은 퉁크족 덕분에 을 열 수 장점이 .getState()바퀴를 재창조할 필요가 없습니다. 이 이 누군가에게 이 될지도
1. 땡크
export const getAxiosConfig = (payload) => {
return (dispatch, getState) => {
const { app } = getState();
const axiosConfig: AxiosRequestConfig = {
baseURL: `${process.env.BACKEND_API}`,
headers: {
Authorization: `Bearer ${app.token}`
}
};
return axiosConfig;
}
}
2. 구성 입수
const axiosConfig = dispatch(가져오기)AxiosConfig(특수);
3. 설정을 사용한 API 호출
{ }=const { data }) = axios.get() = axios.get이다.
/resource/${resourceId}, axiosConfig );
언급URL : https://stackoverflow.com/questions/38460949/what-is-the-best-way-to-access-redux-store-outside-a-react-component
'programing' 카테고리의 다른 글
| JSON 개체를 localStorage 어레이에 푸시 (0) | 2023.03.26 |
|---|---|
| wp_nav_menu에서 '홈' 링크를 삭제하는 방법! (0) | 2023.03.26 |
| 한 페이지 앱에서 잘못된 URL(404 오류)에 대처하는 올바른 방법은 무엇입니까? (0) | 2023.03.26 |
| 같은 방법을 여러 번 연속으로 사용 (0) | 2023.03.21 |
| json 출력에 가상 특성 추가 (0) | 2023.03.21 |