【发布时间】:2021-09-10 20:36:43
【问题描述】:
import React, { useState, useRef, useReducer } from "react";
import "./App.css";
function reducer(state,action){
const {past,present,future} = state
switch(action.type){
case 'ADD' : return {
past : [...past,present],
present : [...present,{id : Math.random(),name : action.payload}],
future : [],
canUndo : true,
canRedo : false,
}
case "UNDO" : if(!state.canUndo) return state;
return {
present :past[past.length - 1],
past : past.slice(0,-1),
future : [present,...future],
canUndo : past.length > 1,
canRede : true
}
case 'REDO' : return {
}
default: return state;
}
}
function App(){
const input = useRef();
const initialState = {
present : [],
past : [],
future : [],
canUndo : false,
canRedo : false,
}
const[items,dispatch] = useReducer(reducer,initialState);
const addItem = (e) => {
e.preventDefault();
dispatch({type : 'ADD', payload : input.current.value})
input.current.value = '';
}
return(
<div>
<h1>Shopping list</h1>
<form className='add-product' onSubmit={addItem}>
<label htmlFOR='product'>product</label>
<input ref={input} type='text' id='product'/>
<button type='submit'>Add</button>
</form>
<div className='actions'>
<button onClick={() => dispatch({type : 'UNDO'})}>Undo</button>
<button onClick={() => dispatch({type : 'REDO'})}>Redo</button>
</div><ul>
{items.present.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
</div>
)
}
export default App;
大家好,我很难理解这个概念
现在:过去[past.length - 1]
所以在添加一个值之后,当我单击撤消按钮时,它应该返回一个值,但是它返回一个完整的数组,除了最后一个,如果有人解释这个概念,我将非常感激,为什么它的行为像切片法
【问题讨论】:
-
我认为问题出在您的一些操作中,您正在像这样连接数组:
[...past,present]-> 在这里,不应该是[...past,...present]。此外,这个future : [present,...future]应该是:future : [...present,...future]。对?我可能是错的,但对我来说就是这样...... -
在codesandbox 中运行您的代码似乎运行正常(据我所知)。问题是什么?你是在问为什么
past[past.length - 1]返回一个数组?
标签: javascript reactjs use-reducer