【问题标题】:React JS maps through wrong propsReact JS 通过错误的 props 映射
【发布时间】:2019-01-04 09:06:57
【问题描述】:

所以我从我的 API 中获取两种类型的关键字,一方面是关键字(用户可以添加)和允许的关键字。到目前为止,我已经做出了动作和减速器,但是当我通过关键字道具进行映射时,它也会以某种方式映射允许的关键字,我不明白为什么......我看不到任何问题,也许我错过了一些东西我看不到关键字和允许的关键字之间的任何联系。

所以这里是代码。 关键字组件:

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
  }
 }

我希望你们能帮助我,我认为我犯了一个愚蠢的错误,所以请宽容:)

【问题讨论】:

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


    【解决方案1】:

    这两种类型的关键字都映射到单个 reducer 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 : []
    }
    

    【讨论】:

    【解决方案2】:

    免责声明:我对 Redux 和 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-22
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2022-09-24
      • 1970-01-01
      • 2021-05-19
      相关资源
      最近更新 更多