我正在重构一些代码,因为我不得不做的道具钻进量是难以控制的,所以我以此为契机来学习Context API,但是我只是不理解为什么状态不是符合我的预期方式...这是我的上下文文件:
import React,{useState, createContext} from 'react';
export const MileContext = createContext();
export const MileProvider = props => {
const [totalMiles, setTotalMiles] = useState(0);
const [drivers, setDrivers] = useState(1);
return (
<MileContext.Provider
value = {
[totalMiles, setTotalMiles],
[drivers, setDrivers]
}>
{props.children}
</MileContext.Provider>
)
}
当我从另一个组件中更改totalMiles,然后从另一个组件中更改驱动程序时,它们共享一个值是正确的……这是另外两个组件。
import React, {useState, useContext} from 'react';
import "./main.css";
import { MileContext } from './MileContext';
const TotalDrivers = () => {
const [drivers, setDrivers] = useContext(MileContext);
const onDriverChange = (event) => {
setDrivers(event.target.value)
};
return(
<div>
<p>Total Drivers</p>
<label>
<select value={drivers} onChange={onDriverChange}>
<option value="1">1</option>
<option value="2">2</option>
</select>
</label>
</div>
)
}
export default TotalDrivers;
import React, {useState, useContext} from 'react';
import "./main.css";
import {PRESETS} from "./presets";
import { MileContext } from './MileContext';
const PresetSelector = () => {
const [totalMiles, setTotalMiles] = useContext(MileContext);
const onTotalMileChange = (event) => {
setTotalMiles(event.target.value)
};
return(
<div>
<label>
<h3>Select a preset for your trip (these are round trips from the warehouse and back)</h3>
<select onChange={onTotalMileChange}>
<option value="0">Custom Trip</option>
{
Object.entries(PRESETS).map(([campus, mileage]) => (
<option key={campus} value={mileage}>
{campus}
</option>
))}
</select>
</label>
trip total miles = {totalMiles}
</div>
)
}
export default PresetSelector;
我觉得自己正在弄清楚这一点,但我所有的Google都陷入困境。当然,我只是误解了某些东西,或者没有使用正确的语法。您能帮助我了解如何解决此问题吗?我还有很多其他组件和状态值要添加到此应用程序中。哦,我像这样将它们包装在app.js中:
return (
<MileProvider>
<Header />
<form>
<PresetSelector />
<TotalDrivers />
</form>
</MileProvider>
);
}
答案 0 :(得分:2)
您正在传递对象内的元组,而没有任何无效语法的键。
在将值传递给上下文提供程序时,只需将值作为对象提供即可。
<MileContext.Provider
value = {{
totalMiles,
setTotalMiles,
drivers,
setDrivers
}}>
{props.children}
</MileContext.Provider>
TotalDrivers组件中的用法:
const {drivers, setDrivers} = useContext(MileContext);
PresetSelector组件中的用法
const {totalMiles, setTotalMiles} = useContext(MileContext);