Dispatch 不会立即更新组件
Dispatch doesn't update component instantly
作为参考,我正在学习 this 教程。我的试用应用程序是一个用户管理工具。当前显示用户列表的下面是商店代码。它使用 dispatcher.dispatch({type: "CREATE_USER", name: "Andrew"})
成功地将用户添加到列表中。但是它不会这样做,直到我点击一条路线然后它才会更新。
import { EventEmitter } from "events";
import dispatcher from "../Dispatcher";
class UserManagement extends EventEmitter{
constructor(){
super();
this.users =
[
{
id: 1234,
name: 'Anton',
email: 'escalante.anton@outlook.com'
},
{
id: 12345,
name: 'Bacon',
email: 'bacon@me.com'
}
];
}
getAll(){
return this.users;
}
createUser(name){
const id = Date.now();
this.users.push({
id,
name,
email: 'default@email.com'
});
this.emit("change");
}
handleActions(action){
switch(action.type){
case "CREATE_USER":{
this.createUser(action.name);
break;
}
}
}
}
const userobj = new UserManagement;
dispatcher.register(userobj.handleActions.bind(userobj));
window.dispatcher = dispatcher;
export default userobj;
编辑 我在想我需要触发状态更改吗?
要重新渲染数据,您应该通过调用 setState 或使用 forceUpdate 强制渲染来触发渲染
请注意,不推荐使用 forceUpdate,您的组件读取存储数据的正确方法是将数据复制到状态并从中读取this.state 在渲染函数中。
作为参考,我正在学习 this 教程。我的试用应用程序是一个用户管理工具。当前显示用户列表的下面是商店代码。它使用 dispatcher.dispatch({type: "CREATE_USER", name: "Andrew"})
成功地将用户添加到列表中。但是它不会这样做,直到我点击一条路线然后它才会更新。
import { EventEmitter } from "events";
import dispatcher from "../Dispatcher";
class UserManagement extends EventEmitter{
constructor(){
super();
this.users =
[
{
id: 1234,
name: 'Anton',
email: 'escalante.anton@outlook.com'
},
{
id: 12345,
name: 'Bacon',
email: 'bacon@me.com'
}
];
}
getAll(){
return this.users;
}
createUser(name){
const id = Date.now();
this.users.push({
id,
name,
email: 'default@email.com'
});
this.emit("change");
}
handleActions(action){
switch(action.type){
case "CREATE_USER":{
this.createUser(action.name);
break;
}
}
}
}
const userobj = new UserManagement;
dispatcher.register(userobj.handleActions.bind(userobj));
window.dispatcher = dispatcher;
export default userobj;
编辑 我在想我需要触发状态更改吗?
要重新渲染数据,您应该通过调用 setState 或使用 forceUpdate 强制渲染来触发渲染
请注意,不推荐使用 forceUpdate,您的组件读取存储数据的正确方法是将数据复制到状态并从中读取this.state 在渲染函数中。