2017-10-26 5 views
0

반응 구성 요소 (즉, 별도의 도우미 함수) 외부에 저장소 인스턴스 (저장소 상태)를 가져 오려고합니다. 내 감속가, 나의 행동, 나는 가장 위의 구성 요소에 상점을 만들었습니다. React Redux - 헬퍼 함수에서 기존 저장소에 액세스

configStore.js 
 

 
import { createStore } from 'redux'; 
 
import generalReducers from '../reducers/generalReducers'; 
 

 
export default function configStore(initialState) { 
 
    return createStore(generalReducers, initialState); 
 
} 
 

 
index.js 
 

 

 
import { Provider } from 'react-redux'; 
 
import configStore from './store/configStore'; 
 

 
const initialReduxStoreConfig = { 
 
    unit: 'm2', 
 
    language: 'en' 
 
} 
 

 
const store = configStore(initialReduxStoreConfig); 
 

 
ReactDOM.render((
 
    <Provider store={store}> 
 
     <App/>  
 
    </Provider> 
 
), document.querySelector('#root')); 
 

 
helpers.js 
 

 
import configStore from '../store/configStore'; 
 

 
const store = configStore(); 
 

 
function getTranslation(key, lang = null) { 
 
    console.log(store.getState()); 
 
}

는 이러한 접근 방식은 (store.getState()) undefined를 반환 CONSOLE.LOG으로 작동하지 않습니다. 그러나 configStore()에 initialConfig를 전달하면 새 저장소가 만들어지고 모든 것이 잘 작동합니다.

도움 주셔서 감사합니다.

+0

스토어 초기화 코드를 별도의 모듈로 옮기고, 스토어를 내보내고, 필요할 때마다 가져올 수 있습니다. – Flying

+0

좀 더 구체적으로 알려주시겠습니까? 별도의 파일에 저장소를 만들고 있는데, index.js의 configStore() 함수를 호출하고 있습니다. – DavidN

+0

아래 예제에서 해결책을 찾으십시오. – Flying

답변

1

index.jshelpers.js으로 별도의 상점을 생성하므로 동일한 Redux 스토어를 사용해야하므로 현재 코드가 작동하지 않습니다.

스토어 초기화 코드를 별도의 모듈로 옮기고 스토어를 내보내고 필요할 때마다 가져올 수 있습니다.

// configStore.js 
import {createStore} from 'redux'; 
import generalReducers from '../reducers/generalReducers'; 

export default function configStore(initialState) { 
    return createStore(generalReducers, initialState); 
} 

// store.js 
import configStore from './store/configStore'; 

const initialReduxStoreConfig = { 
    unit: 'm2', 
    language: 'en' 
} 

const store = configStore(initialReduxStoreConfig); 

export default store; 

// index.js 
import {Provider} from 'react-redux'; 
import store from './store'; 

ReactDOM.render((
    <Provider store={store}> 
     <App/> 
    </Provider> 
), document.querySelector('#root')); 

// helpers.js 
import store from './store'; 

function getTranslation(key, lang = null) { 
    console.log(store.getState()); 
} 
+0

놀라운 사람, 매력처럼 작동합니다! 도와 주셔서 감사합니다 :) – DavidN