现在我在减速机中执行以下操作:
export default function (state = null, action) {
if(state==null)
{
state = [
{
id: 1,
first: "Bucky",
last: "Roberts",
age: 71,
description: "Bucky is a React developer and YouTuber",
thumbnail: "http://i.imgur.com/7yUvePI.jpg"
},
{
id: 2,
first: "Joby",
last: "Wasilenko",
age: 27,
description: "Joby loves the Packers, cheese, and turtles.",
thumbnail: "http://i.imgur.com/52xRlm8.png"
},
{
id: 3,
first: "Madison",
last: "Williams",
age: 24,
description: "Madi likes her dog but it is really annoying.",
thumbnail: "http://i.imgur.com/4EMtxHB.png"
}
]
}
switch (action.type) {
case 'USER_DELETED':
return state.filter(user => user.id !== action.userIdToDelete);
}
return state;
}
所以我检查状态是否为null,如果是,则填充它。有没有更好的方法来做到这一点,即不从内部填充我的减速机?对我来说看起来很糟糕......
答案 0 :(得分:1)
不要将默认值设为null - 请执行以下操作
initialState = [
{
id: 1,
first: "Bucky",
last: "Roberts",
age: 71,
description: "Bucky is a React developer and YouTuber",
thumbnail: "http://i.imgur.com/7yUvePI.jpg"
},
{
id: 2,
first: "Joby",
last: "Wasilenko",
age: 27,
description: "Joby loves the Packers, cheese, and turtles.",
thumbnail: "http://i.imgur.com/52xRlm8.png"
},
{
id: 3,
first: "Madison",
last: "Williams",
age: 24,
description: "Madi likes her dog but it is really annoying.",
thumbnail: "http://i.imgur.com/4EMtxHB.png"
}
];
export default function (state = initalState, action) {
...
}
答案 1 :(得分:1)
您应该始终将默认状态值设置为您期望的类型,因此function (state=[])
更好。将其设置为null是一种反模式。
然后,对于数据作为默认初始状态,您应该使用createStore中的第二个参数来设置初始状态:http://redux.js.org/docs/api/createStore.html