小编Shu*_*ala的帖子

如何用react hooks完全替代redux?

我正在考虑使用 React hooks [useReducer, useContext] 和 context api 来代替 redux。话虽如此,我希望我的状态在结构上有点复杂。让我们看看结构是这样的

state = {
    key1: true,
    key2: {
        key3: [],
        key4: ''
    }
}
Run Code Online (Sandbox Code Playgroud)

我清楚的是 redux 和 context api 都允许我创建复杂的结构。在使用 React hooks 的情况下,我可以很好地使用 Provider、Consumer/useContext 将我的存储状态值传递给我的所有组件。

Redux 给我带来的更多好处是,如果key4更新了任何特定的键 , ,那么可以帮助我不用使用 中的 connect 函数重新渲染整个应用程序树react-redux。这是我的查询。

我们怎样才能使 React hooks 和 context api 不重新渲染我的整个应用程序,这是一个主要的性能错误?

reactjs react-native redux react-hooks

3
推荐指数
1
解决办法
2947
查看次数

为什么我的reducer在react / redux中返回一个空数组?

在我的reducer中,它返回我从api获取的对象数组。我在列表上做了一个console.log,我可以看到这个数组,但是当我访问我的react类中的reducer时,它显示为一个空数组,为什么会这样呢?在我的react文件的render()函数内部,它确实出于某种奇怪的原因而打印,但是我有一个函数试图使用化简器中的数据来渲染单独的div,并且数组显示为空。

getList() {
        let arr = [];
        if(this.props.popular){
            arr = this.props.popular.map(item => {
                return (
                    <div key={item.id} className="movie">
                        <img
                            src={`https://image.tmdb.org/t/p/w300${item.poster_path}`}
                            //onClick={() => this.displayModal(item)}
                        />
                    </div>)
            })
        }
        // console.log(arr)
        // this.props.updateCurrentShowList(arr);
        return arr;
    }
Run Code Online (Sandbox Code Playgroud)

我从下面使用的mapstatetoprops函数中使用this.props.popular。

import { FETCH_POPULAR, RESET_POPULAR } from "../Actions/types";

let initialList = [];

export default function(state = initialList, action){
    switch(action.type){
        case FETCH_POPULAR:
            //return action.payload || false;
            initialList = initialList.concat(...action.payload);
            //console.log(initialList);
            return initialList;

        case RESET_POPULAR:
            initialList = action.payload;
            return initialList;

        default:
            return state;
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里initialList被打印并工作,然后我将其返回。

这是我在要访问该数组的其他文件中拥有的mapStateToProps函数。我在我的reducers文件中使用了Combinereducers。

function …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs redux

2
推荐指数
1
解决办法
1522
查看次数

标签 统计

reactjs ×2

redux ×2

javascript ×1

react-hooks ×1

react-native ×1