通过错误的道具来响应JS地图

时间:2018-07-27 09:10:40

标签: reactjs rest api react-router react-redux

所以我要从我的API中提取两种类型的关键字,一方面是关键字(用户可以添加)和允许的关键字。到目前为止,我已经做出了动作和归约,但是当我通过关键字props映射时,它也以某种方式映射了被允许的关键字,而且我不明白为什么...我看不到任何问题,也许我缺少了一些东西,我看不到关键字和允许的关键字之间的任何连接。

这是代码。 关键字组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { keywords, auth } from '../actions';

class Keyword extends Component {

    componentDidMount() {
        this.props.fetchKeywords();
        this.props.fetchAllowedKeywords();
    }
    render() {
        if(this.props.auth.isAuthenticated) {
            return (
                    <div> 
                        <div>

                        </div>
                        <div>
                        {this.props.keywords.map((keyword) => (
                            <span key={`keyword_${keyword.id}`} className="btn btn-primary text-light">{keyword.keyword}</span> //I dont know why, but it displays also the allowed_keywords
                        ))} 
                        </div>
                    </div>
                )
        } else if(!this.props.auth.isLoading) {
            return <p> Please login to customize your news feed. </p>
        }

    }

}

const mapStateToProps = state => {
    return {
        keywords: state.keywords,
        allowed_keywords: state.allowed_keywords,
        user: state.auth.user,
        auth: state.auth,
   }
}

const mapDispatchToProps = dispatch => {
    return {
        fetchKeywords: () => {
            dispatch(keywords.fetchKeywords());
        },
        fetchAllowedKeywords: () => {
            dispatch(keywords.fetchAllowedKeywords());
        },
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Keyword); 

动作:

export const fetchKeywords = () => {
  return (dispatch, getState) => {
    let headers = {'Content-Type': 'application/json'}
    let {token} = getState().auth

    if (token) {
      headers['Authorization'] = `Token ${token}`
    }

    return fetch('/api/keywords/', {headers })
      .then(res => {
        if (res.status < 500) {
          return res.json().then(data => {
            return {status: res.status, data}
          })
        } else {
          console.log('Server Error!')
          throw res
        }
      })
      .then(res => {
        if (res.status === 200) {
          return dispatch({type: 'FETCH_KEYWORDS', keywords: res.data})
        } else if (res.status === 401 || res.status === 403) {
          dispatch({type: 'AUTHENTICATION_ERROR', data: res.data})
          throw res.data
        }
      })
  }
}

export const fetchAllowedKeywords = () => {
  return (dispatch, getState) => {
    let headers = {'Content-Type': 'application/json'}
    let {token} = getState().auth

    if (token) {
      headers['Authorization'] = `Token ${token}`
    }

    return fetch('/api/allowedkeywords/', {headers })
      .then(res => {
        if (res.status < 500) {
          return res.json().then(data => {
           return {status: res.status, data}
          })
        } else {
          console.log('Server Error!')
          throw res
        }
      })
      .then(res => {
        if (res.status === 200) {
          return dispatch({type: 'FETCH_ALLOWEDKEYWORD', allowed_keywords: 
          res.data})
        } else if (res.status === 401 || res.status === 403) {
          dispatch({type: 'AUTHENTICATION_ERROR', data: res.data})
          throw res.data
        }
      })
  }
}

和减速器:

const initialState = []

export default function keywords (state = initialState, action) {
  // let keywordList = state.slice();

  switch (action.type) {
    case 'FETCH_KEYWORDS':
        return [...state, ...action.keywords]

    case 'FETCH_ALLOWEDKEYWORD':
        return [...state, ...action.allowed_keywords]

    default:
      return state
  }
 }

我希望你们能帮助我,我想我犯了一个愚蠢的错误,所以请放纵:)

2 个答案:

答案 0 :(得分:2)

这两种关键字都映射到单个归约器keywords中。

无法区分这两种类型的关键字。

case 'FETCH_KEYWORDS':
        return [...state, ...action.keywords]

    case 'FETCH_ALLOWEDKEYWORD':
        return [...state, ...action.allowed_keywords]

在mapStateToProps中, 它将获取映射到单个状态的两种关键字。

keywords: state.keywords, //will fetch all keywords

最好将这些关键字映射到相同精简器中的差异键中。

case 'FETCH_KEYWORDS':
    return {...state, keywords:[...state.keywords,...action.keywords]}

case 'FETCH_ALLOWEDKEYWORD':
    return [...state, allowed_keywords:{...state.allowed_keywords,action.allowed_keywords]}

在mapStateToProps中,

keywords: state.keywords.keywords,
allowed_keywords: state.keywords.allowed_keywords

编辑:

添加

initialState = {
  keywords: [],
 allowed_keywords : []
}

答案 1 :(得分:1)

免责声明:我对Redux和Reducer只是一个理论上的理解。

您的reducer似乎只是返回array而不是状态表示/突变。根据官方documentation,我认为应该是:

const initialState =  {
    keywords: [],
    allowed_keywords: [],
    user: null,
    auth: {},
 }

export default function keywords (state = initialState, action) {
// let keywordList = state.slice();

   switch (action.type) {
      case 'FETCH_KEYWORDS':
       return Object.assign({}, state, {keywords: [...keywords]})

      case 'FETCH_ALLOWEDKEYWORD':
        return Object.assign({}, state, {allowed_keywords: [...keywords]})

      default:
        return state
    }
}