【发布时间】:2020-12-28 17:22:36
【问题描述】:
第一个 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();
}
}
function Fees() {
const [state, dispatch] = useReducer(reducer, [])
return (
<body>
<h1>Fees {state}</h1>
<p>
<button onClick={() => dispatch({ type: 'add', item: prompt('Expense?') + prompt('Amount?') })}>+</button>
<button onClick={() => dispatch({ type: 'rm', index: prompt<number>('line number?') - 1 })}>-</button>
<table>
<tr>
<th>
Expense
</th>
<th>
Amount
</th>
{state.map((item) => {
<td> {item}</td>
})}
</tr>
<tr><td>Total</td></tr>
</table>
</p>
</body>
)
}
export default Fees
【问题讨论】:
-
您采取了什么措施在第一个和第二个文件中填充
state? -
概念
useReducerreactjs.org/docs/hooks-reference.html#usereducer -
我在他们两个中都填写了提示
-
您发现我的减速器有问题吗?因为我没有
-
它是从待办事项列表中复制粘贴而来的(第一个代码)
标签: javascript reactjs typescript jsx