내 상점에 나는이 모양의 상태가 있습니다 : {posts: [{...},{...}]}
,하지만 Home.js에서 mapStateToProps()
을 사용할 때 상태는 {posts: []}
이고 빈 배열 (저장소 상태의 배열이 있었던 곳)이 반환됩니다.React/Redux : mapStateToProps()가 배열의 저장소 상태를 사라지게하는 이유는 무엇입니까?
mapStateToProps()
을 잘못 사용하고 있습니까? 아니면 문제가 Redux주기의 다른 부분에서 비롯된 것입니까?
// actions.js
export const REQUEST_POSTS = 'REQUEST_POSTS';
function requestPosts (posts) {
return {
type: REQUEST_POSTS,
posts
}
}
export const RECEIVE_POSTS = 'RECEIVE_POSTS';
function receivePosts (posts) {
return {
type: RECEIVE_POSTS,
posts,
receivedAt: Date.now()
}
}
// thunk middleware action creator, intervenes in the above function
export function fetchPosts (posts) {
return function (dispatch) {
dispatch(requestPosts(posts))
return getAllPosts()
.then(
res => res.json(),
error => console.log('An error occured.', error)
)
.then(posts =>
dispatch(receivePosts(posts))
)
}
}
감속기 :
API는 썽크 미들웨어를 사용하여, 나는 일시적으로 actions.js에
// api
const API = "http://localhost:3001"
let token = localStorage.token
if (!token) {
token = localStorage.token = Math.random().toString(36).substr(-8)
}
const headers = {
'Accept': 'application/json',
'Authorization': token
}
// gets all posts
const getAllPosts = token => (
fetch(`${API}/posts`, { method: 'GET', headers })
);
행동과 행동 제작자에 위치, 사용하고 가져
// rootReducer.js
function posts (state = [], action) {
const { posts } = action
switch(action.type) {
case RECEIVE_POSTS :
return posts;
default :
return state;
}
}
일시적으로 돌아 오는 저장소를 포함
루트 구성 요소 :
// index.js (contains store)
const store = createStore(
rootReducer,
composeEnhancers(
applyMiddleware(
logger, // logs actions
thunk // lets us dispatch() functions
)
)
)
store
.dispatch(fetchPosts())
.then(() => console.log('On store dispatch: ', store.getState())) // returns expected
ReactDOM.render(
<BrowserRouter>
<Provider store={store}>
<Quoted />
</Provider>
</BrowserRouter>, document.getElementById('root'));
registerServiceWorker();
주성분 :
Home.js 구성 요소에서// Home.js
function mapStateToProps(state) {
return {
posts: state
}
}
export default connect(mapStateToProps)(Home)
, console.log('Props', this.props)
반환 {게시물 : []} 나는 {posts : [{...}, {...}}}을 기대한다.
*** 편집 : 발송하기 전에 행동에와 감속기에 console.log()
을 추가 한 후 , 여기에 콘솔 출력 다음 REDUX 저장소 오브젝트해야 Console output link (not high enough rep to embed yet)
모든 것이 잘 보인다. 가져 오기 결과가 확실합니까? 디스패치 직전의 액션과 감속기의 액션에'console.log'를 넣을 수 있습니까? – yuantonito
좋은 생각, 나는 그 (것)들을 추가하고 위의 콘솔 출력에 대한 링크를 떨어 뜨렸다 - 가져 오기 반환이 행동, 감속기 및 저장소에서 올바른 것 같지만 구성 요소에서 사라진다. –