第一个 tsx 代码正确显示 state.map,而第二个代码不显示任何内容。为什么?这两段代码以相同的方式做同样的事情,但仍然正确显示了一个列表,而另一个 state.map 从未渲染过任何东西,尽管进行了许多调整
import React from 'react';
import './App.css'
const { useReducer } = require("react");
function reducer(state, action) {
switch (action.type) {
case 'add': return [...state, action.item]
case 'rm': return [...state.slice(0, action.index), ...state.slice(action.index + 1, state.length)]
default: throw new Error();
}
}
function Todo() {
const [state, dispatch] = useReducer(reducer, [])
return (
<div className="App">
<h1>TO DO</h1>
<p>
<button onClick={() => dispatch({ type: 'add', item: prompt('?') })}>+</button>
<button onClick={() => dispatch({ type: 'rm', index: prompt('?') - 1 })}>-</button>
<button onClick={() => dispatch({ type: 'rm', index: prompt('?') - 1 })}></button>
<ol>{
state.map((item) => (
<>{item}</>
))}</ol>
</p>
</div>
)
}
export default Todo
/////////////////////////////////////////////////////////////////
import React from 'react';
const { useReducer } = require("react");
function reducer(state, action) {
switch (action.type) {
case 'add': return [...state, action.item]
case 'rm': return [...state.slice(0, action.index), ...state.slice(action.index + 1, state.length)]
default: throw new Error();
}
}
喵喵时光机
哈士奇WWW
相关分类