【发布时间】:2018-09-23 08:34:40
【问题描述】:
*这是一个 React-Redux 教程,所以请不要其他解决方案:)
期望的行为:将父组件的 props 从 redux 控制的状态传递给 PostDetail 组件
电流输出:
(1) 204 结果:
http://localhost:3001/react/8xf0y6ziyjabvozdd253nd
Request Method: OPTIONS
**strong text**Status Code: 204 No Content
(2) 控制台错误:
GET http://localhost:3001/react/8xf0y6ziyjabvozdd253nd 404 (Not Found)
:3000/react/8xf0y6ziyjabvozdd253nd:1
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
在我的应用程序 (root.js) 文件中,我有想要路由到的 PostDetail 组件,如下所示:
import React, { Component } from 'react';
import { Route } from 'react-router-dom'
import Categories from './Categories'
import ListPosts from './ListPosts'
import Header from './Header'
import PostDetail from './PostDetail'
class App extends Component {
render() {
return (
<div>
<Header />
<Categories />
<ListPosts />
<Route exact path="/:category/:id" component={PostDetail}/>
</div>
然后在 PostDetail 嵌套组件中(在 ListPosts 组件内)我在 material-ui flatbutton 内有一个函数,(重要的旁注:PostDetail 组件确实有一个正在调用的 console.log 语句,但是props.post 未定义):
selectPost = (selectedCategory, selectedPost) => {
console.log('selectedCategory', selectedCategory, selectedPost)
this.props.getSpecificPost(selectedCategory, selectedPost);
}
return (
<CardActions>
<FlatButton
label="See Thread"
// href={`/${post.category}/${post.id}`}
containerElement={<Link to={`/${post.category}/${post.id}`} post={this.props.post} />}
onClick={() => this.selectPost(post.category, post.id)}
/>
)
在同一个组件中是我的 mapStateToProps 和 mapDispatchToProps:
const mapStateToProps = state => ({
posts: state.postsReducer.posts,
loading: state.postsReducer.loading,
error: state.postsReducer.error,
selectedCategory: state.categoriesReducer.selectedCategory,
selectedPost: state.postsReducer.selectedPost,
});
function mapDispatchToProps (dispatch) {
return {
getSpecificPost: (selectedCategory, selectedPost) =>
dispatch(getSpecificPost(selectedCategory, selectedPost)),
fetchPosts: (selectedCategory) => dispatch(fetchPosts(selectedCategory))
}
}
export default withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(PostPreview))
我正在使用调用我的 api 的 redux-thunk 操作调用:
export function getSpecificPost(selectedCategory, selectedPost) {
console.log('getSpecificPost', selectedPost)
return dispatch => {
dispatch(beginFetchPosts());
return fetch(selectedPost ? `${api}/${selectedCategory}/${selectedPost}`
: null, { headers })
.then(
res => res.json(),
error => console.log('An error occured at getSpecificPost', error)
)
.then(json => {
dispatch(selectPostSuccess(json));
return json
})
}
}
还有一个减速器:
const initialState = {
posts: [],
categories: [],
loading: false,
error: null,
selectedCategory: 'all',
selectedPost: [],
};
export function postsReducer(state = readableInitialState, action) {
switch(action.type) {
case C.SELECTED_POST:
return {
...state,
loading: false,
selectedPost: action.payload.selectedPost
};
...是的,我使用默认语句完成 switch 语句,据我所知没有语法问题)
【问题讨论】:
标签: reactjs react-router react-redux redux-thunk