【问题标题】:How to toggle state by unique string in react redux?如何通过反应 redux 中的唯一字符串切换状态?
【发布时间】:2020-11-10 09:14:34
【问题描述】:

我在 thunk 中间件的帮助下通过映射来自 JSON 响应的数据来动态地在组件文件中创建一个列表。 我想从该列表中选择元素并将它们添加到“我的收藏夹”中, 我的 JSON 响应没有唯一的 ID,而是唯一的字符串。

减速机:

   const initialstate = { isFav: false }
   const reducer = (state=initialstate, action) => {
   switch(action.type){
   case actionTypes.TOGGLE_FAVORITE:
             return {
              ...state,
              isFav: **What to do here?**
             }
                     
         default:
             break;
         }
    }

export default reducer;

Action.js:

export const TOGGLE_FAVORITE = 'TOGGLE_FAVORITE';
export const togglefav = (url) =>{
    return{
        type: TOGGLE_FAVORITE,
        payload: url
    }
}

组件.js

this.props.dailySource.map((source,index) =>{
...
<div className={classes.star}>
            <span className="fa fa-star" key={index} onClick={()=>             
            this.props.onToggleFavorite(source.url) }
            style={{ color: (this.props.toggleFav) ? 'red' : '' }}></span>
            </div>
}
}))

const mapStateToProps = state =>{
  return{
    dailySource: state.list.newsItem,
    toggleFav: state.list.isFav 
  }
}

const mapDispatchToProps = dispatch =>{
  return{
    onToggleFavorite: (url) => dispatch (actionCreators.togglefav(url))
  }
}

【问题讨论】:

    标签: javascript reactjs redux react-redux reducers


    【解决方案1】:

    如果你能简化你的模式会更好。

    与其将 isFav 提取到另一个状态树,不如将它放在列表本身的对象中会容易得多。

    让我们看看代码。

    减速器

    const initialState = [];
    
    const reducer = (state=initialState, action) => {
        switch(action.type) {
            case actionTypes.TOGGLE_FAVORITE:
                const dailySource = [...state].map((v) => {
                    if (v.url === action.url) {
                        v.isFav = true;
                    }
                return v;
                });
                return dailySource;
            default:
                return state;
        }
    }
    

    组件

    this.props.dailySource.map((source,index) =>{
    <div className={classes.star}>
                <span className="fa fa-star" key={index} onClick={()=>             
                this.props.onToggleFavorite(source.url) }
                style={{ color: source.isFav ? 'red' : '' }}></span>
                </div>
    }
    }))
    

    【讨论】:

    • 这是一个好方法。即使它不起作用,我也更接近解决方案。谢谢。
    • 请澄清为什么它不起作用,我也会进一步详细说明。甚至可以做一个迷你回购仅供参考。谢谢
    猜你喜欢
    • 2017-05-24
    • 2019-06-15
    • 2014-01-30
    • 1970-01-01
    • 2010-10-20
    • 2021-05-09
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    相关资源
    最近更新 更多