[英]How to re-render react functional component when a promise is resolved
I'm trying to figure out a simple todo app in react using typescript.我正在尝试使用 typescript 找出一个简单的待办事项应用程序。 the newly created todo doesn't reflect on the list.
新创建的待办事项不会反映在列表中。 am trying to figure out what went wrong here
我想弄清楚这里出了什么问题
my react component我的反应组件
const service = new TodoService();
function App() {
useEffect(()=>{
service.getAllTodos();
});
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<TodoContainer items={service.allTodos} onNewTodoCreated={description => {service.createTodo(description)}} />
</header>
</div>
);
}
export default App;
the TodoContainer takes list of items and newtodoCreated as props TodoContainer 将项目列表和 newtodoCreated 作为道具
and my service和我的服务
export default class TodoService {
public allTodos: TodoItem[] = [
{dateCreated: new Date(), id: v4(), description: "Fetch Milk" },
{dateCreated: new Date(), id: v4(), description: "Buy iPhone" },
{dateCreated: new Date(), id: v4(), description: "Impress at DWIT" },
]
getAllTodos(): Promise<TodoItem[]> {
return new Promise<TodoItem[]>((resolve) => {
setTimeout(() => resolve(this.allTodos), 3000);
});
}
createTodo(description: string): Promise<TodoItem> {
return new Promise<TodoItem>((resolve) => {
const id = uuidv4();
const dateCreated = new Date();
setTimeout(() => {
const saved = {description, id, dateCreated};
this.allTodos.push(saved);
resolve(saved);
}, 2000);
})
}
}
You need to use useState hook here, something like so你需要在这里使用useState钩子,像这样
function App() { const [todos, setTodos] = useState([]); useEffect(()=>{ service.getAllTodos().then(todos => setTodos(todos)); }, []); const handleCreate = (description) => service.createTodo(description).then(todo => { /* @TODO update state */ }) } return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <TodoContainer items={todos} onNewTodoCreated={handleCreate} /> </header> </div> ); } export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.