跳到主要内容

语法

2024年03月11日
柏拉文
越努力,越幸运

一、useImmer


import { useImmer } from "./hooks/useImmer";

function App() {
const [form, setForm] = useImmer({
a: "",
b: {
c: {
d: "",
},
},
});

const handleInputChange = (e: any) => {
const { value } = e.target;
setForm((draft)=>{
draft.b.c.d = value;
});
};

return (
<div>
<input value={form.b.c.d} onChange={handleInputChange}></input>
</div>
);
}

export default App;

二、useState + immer


import { useState } from 'react';
import { produce } from "immer";

function App() {
const [form,setForm] = useState({
a: "",
b: {
c: {
d: ""
}
}
})

const handleInputChange = (e: any)=>{
const { value } = e.target;
const formNew = produce(form,(draft)=>{
draft.b.c.d = value;
});
setForm(formNew);
}

return (
<div>
<input value={form.b.c.d} onChange={handleInputChange}></input>
</div>
)
}

export default App

三、userImmerReducer


import { useImmerReducer,ImmerReducer } from "./hooks/useImmerReducer";

const initialState = {
a: "",
b: {
c: {
d: "",
},
},
}



const reducer:ImmerReducer<any,any> = (draft, action) => {
switch (action.type) {
case "change":
draft.b.c.d = action.value;
break;
default:
break;
}
}

function App() {
const [form, dispatch] = useImmerReducer(reducer, initialState);

const handleInputChange = (e: any) => {
const { value } = e.target;
dispatch({
type: "change",
value,
});
};

return (
<div>
<input value={form.b.c.d} onChange={handleInputChange}></input>
</div>
);
}

export default App;

四、useReducer + immer


import { produce } from "immer";
import { useReducer } from "react";

const initialState = {
a: "",
b: {
c: {
d: ""
}
}
}

const reducer = produce((draft,action)=>{
switch(action.type){
case "change":
draft.b.c.d = action.value;
break;
default:
break;
}
})

function App() {
const [ form,dispatch ] = useReducer(reducer,initialState);

const handleInputChange = (e: any) => {
const { value } = e.target;
dispatch({
type: "change",
value
});
};

return (
<div>
<input value={form.b.c.d} onChange={handleInputChange}></input>
</div>
);
}

export default App;