繁体   English   中英

我可以在 React + Redux 中使用 props 设置初始状态吗?

[英]Can I Set Initial State with Props in React + Redux?

我遇到了一个问题,我的状态显示为未定义,我怀疑这可能是因为我将初始状态作为道具传递。

下面是 useState 语句的样子:

const [filteredData, setData] = useState(props.cardsToShow);

我将 cardToShow 作为在 MapStateToProps 中定义的状态,如下所示

cardsToShow: searchCards(state)

它是根据我拥有的以下搜索语句进行填充的。 请注意,棒球是初始数据加载,搜索是商店中的搜索查询。

const searchCards = ({ baseball, search }) => {
  return search
    ? baseball.filter(a =>
        a.title[0].toLowerCase().includes(search.toLowerCase())
      )
    : baseball;
};

如果我控制台日志props.cardsToShow我得到数据,它是一个数组对象。

如果我控制台记录filteredData我会得到一个空对象。

有任何想法吗?

Redux 有多种实现方式,您可以使用默认参数为您的 reducer 设置初始状态。

const defaultState = {
    state: 0
}

function counter(state = defaultState, action) {
...

或者,如果您使用选择器

const getSomeValues = store => store.someValue || 1

如果someValueundefined ,我们将得到 1 。

更深入的解释: https : //redux.js.org/recipes/structuring-reducers/initializing-state

如果你使用 lodash,它有get函数,如果属性返回 undefined,它允许你指定默认值。 https://lodash.com/docs/#get

如果我理解得很好,您将面临下面介绍的问题。

根据这篇文章:

https://learnwithparam.com/blog/how-to-pass-props-to-state-properly-in-react-hooks/

useState 不会在 props 更改时初始化,因此您应该在 useEffect 上设置状态

useEffect(() => {
    setData(props.cardsToShow);
}, [props]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM