使用react-routerv4在react-redux app中从状态渲染组件时出现404错误?

时间:2018-04-13 04:22:24

标签: reactjs react-router react-redux redux-thunk

*这是一个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))

我正在使用正在调用我的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语句,据我所知没有语法问题。

2 个答案:

答案 0 :(得分:1)

每当我看到错误

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

我在第一次设置项目并为开发人员点击远程服务器时遇到了CORS问题的闪回问题。

从chrome dev工具转到此页面时,您能提供网络响应吗?在JSON开头应该没有<所以我认为你没有反应路由器问题但是某种服务器配置问题。

答案 1 :(得分:1)

问题是您没有提及该方法,无论是GETPUT,这就是服务器正在考虑OPTIONS的原因。您可以通过其他方式使用fetch来电。

export function getSpecificPost(selectedCategory, selectedPost){
  return (dispatch) => {
    const baseURL = selectedPost ? `${api}/${selectedCategory}/${selectedPost}` : null 
    fetch(baseURL, {
      method: 'GET',
      headers: {
        'content-type': 'application/json'
      },
      body: JSON.stringify(`${headers}`)
    })
    .then(json => {
      dispatch(selectPostSuccess(json))
    })
  } 
}

您还可以通过以下代码段将数据发送到reducer而不是json。

export function getSpecificPost(selectedCategory, selectedPost){
  return (dispatch) => {
    const baseURL = selectedPost ? `${api}/${selectedCategory}/${selectedPost}` : null 
    fetch(baseURL, {
      method: 'GET',
      headers: {
        'content-type': 'application/json'
      },
      body: JSON.stringify(`${headers}`)
    })
    .then(json => response.json())
    .then(data => {
      dispatch(selectPostSuccess(data))
    })
  } 
}

我希望这可以帮到你。