问题描述
第一个jsx / 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,state.length)]
default: throw new Error();
}
}
function Fees() {
const [state,[])
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
解决方法
我看到函数prompt
已声明:
declare function prompt(message?: string,_default?: string): string | null;
您可以稍后删除返回值的类型赋值,然后再进行int验证:
<button onClick={() => dispatch({ type: 'rm',index: prompt('line number?') - 1 })}>-</button>