React TS-禁止手动更改状态

时间:2019-11-23 19:08:06

标签: typescript react-hooks

是否有一种方法可以禁止手动更改状态并仅允许使用setState?

const App = (props) => {
 const [data, setData] = useState({x: 1})

 data.x = 2 // how to forbid this?
 setData({x: 2}) // it's ok
}

还是唯一的方法是使用Readonly接口?

interface ReadOnlyX {
   readonly x: number
}

const App = (props) => {
   const [data, setData] = useState<ReadOnlyX>({x: 1})
   data.x = 2 // forbidden
   setData({x: 2}) // it's ok
}

0 个答案:

没有答案