有使用react、redux、react-redux、redux-thunk的应用程序。
react: "16.0.0-alpha.6"
redux: "3.6.0"
react-redux: "5.0.2"
redux-thunk: "2.1.0"
概念:
reducer :
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
export const MESSAGES_ADD_MESSAGE = 'MESSAGES_ADD_MESSAGE';
export const CONTACTS_ADD_CONTACT = 'CONTACTS_ADD_CONTACT';
export default function messages(state = { messages: [] }, action) {
switch (action.type) {
case MESSAGES_ADD_MESSAGE:
return { messages: [ ...state.messages, action.message ] };
default:
return state;
}
}
export default function contacts(state = { contacts: [] }, action) {
switch (action.type) {
case CONTACTS_ADD_CONTACT:
return { contacts: [ ...state.contacts, action.contact ] };
default:
return state;
}
}
const rootReducer = combineReducers({
contacts,
messages
});
商店:
const createStoreWithMiddleware = applyMiddleware(
thunkMiddleware
)(createStore);
const store = createStoreWithMiddleware(rootReducer);
Action 创建者:
export function addMessage(message) {
return {
type: MESSAGES_ADD_MESSAGE,
message
};
}
export function addContact(contact) {
return {
type: CONTACTS_ADD_CONTACT,
contact
};
}
为什么调度时间(addContact('Viktor +123456789'))会根据存储中的消息数量而增长?
据我了解,在新存储构造时,消息缩减器返回状态引用,而不创建这部分存储的新副本。
我有更复杂的真实案例,但问题的概念是相似的。
最佳答案
每当你改变状态时,它都会创建一个新的副本。如果您想提高性能,您应该使用像 immutable.js 这样的库,它提供了许多优化。
来自文档 -
As described in Reducers, a Redux reducer function:
Should have a signature of (previousState, action) => newState, similar to the type of function you would pass to Array.prototype.reduce(reducer, ?initialValue) Should be "pure", which means the reducer: Does not perform side effects (such as calling API's or modifying non-local objects or variables). Does not call non-pure functions (like Date.now or Math.random). Does not mutate its arguments. If the reducer updates state, it should not modify the existing state object in-place. Instead, it should generate a new object containing the necessary changes. The same approach should be used for any sub-objects within state that the reducer updates.
var makeArray = function ()
{
var temp = [];
for(let i= 0, i < 10000; i++)
temp.push(i);
return temp;
}
var e = makeArray();
var f = makeArray();
function test1()
{ var x = e.push(8);
}
var t2 = performance.now();
test1();
var t3 = performance.now();
t3-t2 //0.02
function test2()
{ var y = [...f, 8]
}
var t2 = performance.now();
test2();
var t3 = performance.now();
t3-t2 //1.98
您可以看到 test2 比 test1 慢。
关于javascript - react redux redux-thunk : dispatch performance issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45464688/