我可以创建一个具有默认值的反冲原子作为对象的对象吗?请参阅以下代码以供参考。
export const formState = atom({
key: "formState",
default: {
name: {
firstName: "",
lastName: ""
}
}
});
可以。这里有一个例子:
TS游乐场
import {default as React} from 'react';
import {atom, useRecoilState} from 'recoil';
const formState = atom({
key: "formState",
default: {
name: {
firstName: "",
lastName: "",
},
},
});
function App (): React.ReactElement {
const [state, setState] = useRecoilState(formState);
const updateFirstName = (firstName: string): void => setState(formState => ({
...formState,
name: {
...formState.name,
firstName,
},
}));
const {firstName} = state.name; // string
return (<div>First name: {firstName}</div>);
}