,可以通过以下步骤实现:
import React, { useContext, useReducer } from 'react';
const MyContext = React.createContext();
const reducer = (state, action) => {
switch (action.type) {
case 'ADD':
return { ...state, [action.key]: action.value };
case 'REMOVE':
const newState = { ...state };
delete newState[action.key];
return newState;
default:
return state;
}
};
const MyComponent = () => {
const [state, dispatch] = useReducer(reducer, {});
const { key1, key2 } = useContext(MyContext);
const handleAdd = () => {
dispatch({ type: 'ADD', key: 'newKey', value: 'newValue' });
};
const handleRemove = () => {
dispatch({ type: 'REMOVE', key: 'newKey' });
};
return (
<div>
<button onClick={handleAdd}>Add Key-Value Pair</button>
<button onClick={handleRemove}>Remove Key-Value Pair</button>
<p>Key 1: {key1}</p>
<p>Key 2: {key2}</p>
</div>
);
};
const App = () => {
return (
<MyContext.Provider value={{ key1: state.key1, key2: state.key2 }}>
<MyComponent />
</MyContext.Provider>
);
};
这样,通过使用useContext和useReducer,我们可以在React中创建新的键值对,并通过dispatch函数来更新键值对的值。在MyComponent组件中,我们可以通过调用dispatch函数来添加或删除键值对。同时,通过使用MyContext.Provider,我们可以将键值对的值传递给子组件。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)和腾讯云云数据库MySQL。
领取专属 10元无门槛券
手把手带您无忧上云