Redux 저장소에 연결된 React 구성 요소가 있습니다. 나는 수명주기 방법 인 componentWillMount
에서 자원 (게시물)을 가져오고 있습니다.Redux를 사용한 비동기 동작
componentWillMount() {
this.props.fetchPosts();
}
구성 요소가 돌아 오는 저장소와 저장소에서 isFetching
및 posts
을 얻기에 가입됩니다.
const mapStateToProps = (state) => {
return {
posts: getAllPosts(state),
isFetching: getIsFetchingPosts(state),
}
}
내가이 일을하고자하는 render
방법, 그래서 여전히 가져 오는 것 스피너를 보여주고 싶습니다.
render() {
if (this.props.isFetching) {
return <Spinner />
}
return this.props.posts.map(post => <PostItem key={post.id}{...post}/>)
}
BUT I는 render
방법을 isFetching
CONSOLE.LOG 경우 제 그러므로 false
하고 true
최종적 false
나타낸다.
이 컨테이너가 처음 렌더링 될 때 isFetching
상태가 이미 true
으로 설정되어 있으며 회 전자를 표시하는 것이 이상적입니다. 그런 일이 일어나기 위해 나는 어떤 변화가 필요합니까? 여기
사전에 감사 조치 작성자에 대한 코드 및 감속기
/*** Action Creator ***/
export const fetchPosts =() => (dispatch) => {
dispatch({
type: REQUEST_POSTS,
});
return axios({
method: 'get',
url: `${API_URL}/posts`,
})
.then(({data}) => {
dispatch({
type: RECEIVE_POSTS,
payload: data.posts,
})
})
.catch((response) => {
// some error handling.
});
}
/*** Reducers ***/
const initialState = {
isFetching: false,
allIds: [],
byId: {},
};
const isFetching = (state = initialState.isFetcthing, action) => {
switch (action.type) {
case REQUEST_POSTS:
return true;
case RECEIVE_POSTS:
return false;
default:
return state;
}
}
const allIds = (state = initialState.allIds, action) => {
switch (action.type) {
case RECEIVE_POSTS:
return action.payload.map(post => post.id);
default:
return state;
}
}
const byId = (state = initialState.byId, action) => {
switch (action.type) {
case RECEIVE_POSTS:
return action.payload.reduce((nextState, post) => {
nextState[post.id] = post;
return nextState;
}, {...state});
default:
return state;
}
}
const posts = combineReducers({
isFetching,
allIds,
byId,
});
export default posts;
/*** Selectors in 'posts.js' file ***/
export const getAllPosts = (state) => {
const { allId, byId } = state;
return allIds.map(id => byId[id]);
}
/*** rootReducer file ***/
import posts, * as fromPosts from './posts';
const rootReducer = combineReducers({
posts,
})
export default rootReducer;
export const getAllPosts = (state) => {
return fromPosts.getAllPosts(state.posts);
};
입니다!
정말 명확하지 않다, 그래서 가상 DOM은 최적화 diffing의 반응 , 당신은 mapStateToProps에 그것을 제공하지 않는다. 그리고 state와 fetchPosts의 게시물 사이의 연결은 무엇입니까 (함수 업데이트 상태입니까?). 이 점을 분명히 해 주시겠습니까? – berliner
처음에'isFetching = false'를 갖는 것은 ok 동작입니다. 즉, 액션이 감속기에 충돌하지 않았 음을 의미합니다. 즉,'fetchPosts'가 플래그를 true로 설정하기 전에'render'가 호출되었습니다. – Igorsvee