代码之家  ›  专栏  ›  技术社区  ›  John

404使用react-routerv4从react redux应用程序中的状态呈现组件时出错?

  •  0
  • John  · 技术社区  · 7 年前

    *这是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语句,据我所知没有语法问题)

    2 回复  |  直到 7 年前
        1
  •  1
  •   William Chou    7 年前

    每当我看到错误

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

    我回想起了CORS问题,在第一次设置项目和为开发人员访问远程服务器时,我必须解决这些问题。

    从chrome开发工具转到此页面时,您能否提供网络响应?应该没有 < 在JSON的开头,我认为您没有react路由器问题,而是服务器配置问题。

        2
  •  1
  •   Thananjaya S    7 年前

    问题是你没有提到这个方法 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))
        })
      } 
    }
    

    您还可以通过以下代码段将数据发送到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))
        })
      } 
    }
    

    我希望这能帮助你。

    推荐文章