Redux Toolkit在调度后不会立即更新。
我接着说:https://redux-toolkit.js.org/tutorials/quick-start
我的代码:
quoteSlice.js
export const quotesSlice = createSlice({
name: 'quotes',
initialState,
reducers: {
setQuotes: (state, action) => {
console.log('before: ', current(state));
state.quotes = action.payload;
console.log('after: ', current(state));
},
},
});
幻灯片.js
const swipeHandlerDelete = async key => {
console.log('swipeHandlerDelete:: ' + key);
// await deleteItem(database, key);
const filteredQuote = await quotes.filter(i => i.id !== key);
console.log('Before++');
console.log('filteredQuote.quote: ' + filteredQuote[0].quote);
console.log('quotes.quote: ' + quotes[0].quote);
await dispatch(setQuotes(filteredQuote));
console.log('After++');
console.log('quotes.quote: ' + quotes[0].quote);
};
结果:在终端
LOG swipeHandlerDelete:: 1
LOG Before++
LOG filteredQuote.quote: I'm well organized and highly productive
LOG quotes.quote: What is the most valuable use of my Time right now
LOG before: {"quotes": [{"created_at": "2022-07-22 10:10:10", "dd": "2022-07-02", "id": 1, "quote": "What is the most valuable use of my Time right now", "status": 1, "updated_at": ""}, {"created_at": "2022-07-22 10:10:10", "dd": "2022-07-02", "id": 2, "quote": "I'm well organized and highly productive", "status": 1, "updated_at": ""}, {"created_at": "2022-07-22 10:10:10", "dd": "2022-07-02", "id": 3, "quote": "Faith can move mountains", "status": 0, "updated_at": ""}]}
LOG after: {"quotes": [{"created_at": "2022-07-22 10:10:10", "dd": "2022-07-02", "id": 2, "quote": "I'm well organized and highly productive", "status": 1, "updated_at": ""}, {"created_at": "2022-07-22 10:10:10", "dd": "2022-07-02", "id": 3, "quote": "Faith can move mountains", "status": 0, "updated_at": ""}]}
LOG After++
LOG quotes.quote: What is the most valuable use of my Time right now
在这里我删除第一个。即key=0
,在此终端结果中,before:和after:得到更新。但在After++中仍然没有改变。为什么以及如何做到这一点?有了这个结果,我必须进一步努力。
到目前为止,我所做的是简单的事情
提示:-在单个功能(滑动/点击/或任何其他移动动作(中,只更新一次redux调度。
错误代码:
if(a > b){
dispatch(setQuotes(a)); // First call
// do some process
var c = newFunction(x);
// do some process
dispatch(setQuotes(c)); // Second call
}
好代码:
const quotes = useSelector(state => state.quotes.quotes);
// ...
if(a > b){
var newQuote = quotes;
// do all process with newQuote
// finally
dispatch(setQuotes(newQuote)); // NOTE: Calling only once
}
你也可以这样做,
const quotes = useSelector(state => state.quotes.quotes);
// ...
if(a > b){
var newQuote = quotes;
// do all process with newQuote
try {
// some process
newQuote = [a,b,c];
dispatch(setValues(a)); // updating setValues only once
} catch (error) {
newQuote = [b,a,c];
dispatch(setValues(b)); // updating setValues only once
}
dispatch(setQuotes(newQuote)); // NOTE: Calling only once
}