*这是React Redux教程,因此请不要使用其他解决方案:)
期望的行为
:将父组件的道具从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
在我的app(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))
我正在使用一个redux thunk操作调用来调用我的api:
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语句,据我所知没有语法问题)