【问题标题】:404 error when rendering component from state in react-redux app with react-routerv4?使用 react-routerv4 从 react-redux 应用程序中的状态渲染组件时出现 404 错误?
【发布时间】: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


    【解决方案1】:

    问题是你没有提到方法,无论是GET,PUT,这就是服务器考虑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))
        })
      } 
    }
    

    你也可以通过以下代码sn-p将数据发送到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))
        })
      } 
    }
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      每当我看到错误时

      Uncaught (in promise) SyntaxError: Unexpected token &lt; in JSON at position 0

      我在第一次设置项目并为开发人员访问远程服务器时不得不解决 CORS 问题。

      当您从 chrome 开发工具转到此页面时,您能否提供您的网络响应? JSON 开头不应该有&lt;,所以我认为您没有反应路由器问题,而是某种服务器配置问题。

      【讨论】:

      • 肯定有一些服务器端不匹配!
      • 很高兴我能帮上忙:) 在我找到 docker 之后,我转而在本地做所有事情。
      猜你喜欢
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      相关资源
      最近更新 更多