我收到錯誤:TypeError: Cannot read property 'map' of undefined
。據我所知,是具有與陣列(posts
)映射到做主持是空的:TypeError:無法讀取undefined |的屬性'map' React,Redux
const postsList = posts.map((postList, i) => {
我的行動看起來是這樣的:
const setPosts = data => {
return {
type: 'SET_POSTS',
payload: {
setPosts: data
}
}
}
export const fetchPosts =() => async dispatch => {
try {
const posts = await axios.get(`${settings.hostname}/api/posts`)
dispatch(setPosts(posts.data))
} catch (err) {
throw err
}
}
我減速機:
const initialState = {}
export const fetchPosts = (state = initialState, action) => {
switch (action.type) {
case 'SET_POSTS':
return { ...state, posts: action.payload.setPosts }
default:
return state
}
}
而且在我的組件(最重要的東西):
componentDidMount() {
this.props.fetchPosts()
}
PostLayout.propTypes = {
props: PropTypes.object.isRequired,
fetchPosts: PropTypes.func.isRequired
}
const mapStateToProps = state => {
return {
posts: state.fetchPosts.posts,
isLoading: state.fetchPostsIsLoading
}
}
const mapDispatchToProps = dispatch => {
return {
fetchPosts:() => dispatch(fetchPosts())
}
}
怪異的是,我可以在這裏看到:
const posts = this.props.posts || []
console.log(posts)
首先它的空數組,但後來它被填滿數據。所以我想知道如何解決這個令人沮喪的錯誤,以便能夠映射我的數據。
感謝您的閱讀!
我的反應是沒有達到標準,我猜這些文件是如何彼此依賴和跟蹤事情的經過,但我看到很清楚,'fetchPosts()'在'action'文件返回一個承諾。你可能可以通過這個承諾,所以你可以做'。然後(/ *得到我的道具* /)' – skylize