使用 Context API 管理状态
2020-04-30
55
我正在重构一些代码,因为我需要进行的 props 钻取量实在是难以管理,所以我借此机会了解了 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,然后从另一个组件更改 drivers 时,显然它们共享一个值...这是另外两个组件。
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;
我觉得我快要弄清楚了,但我所有的谷歌搜索都失败了。肯定是我只是误解了某些东西或者没有使用正确的语法。你能帮我了解如何解决这个问题吗?我有许多其他组件和状态值要添加到这个应用程序中。哦,我将它们包装在 app.js 中,如下所示:
return (
<MileProvider>
<Header />
<form>
<PresetSelector />
<TotalDrivers />
</form>
</MileProvider>
);
}
1个回答
您正在传递对象内的元组,但没有任何键,这是无效的语法。
在将值传递给上下文提供程序时,只需将值作为对象提供即可。
<MileContext.Provider
value = {{
totalMiles,
setTotalMiles,
drivers,
setDrivers
}}>
{props.children}
</MileContext.Provider>
TotalDrivers 组件中的用法:
const {drivers, setDrivers} = useContext(MileContext);
PresetSelector 组件中的用法
const {totalMiles, setTotalMiles} = useContext(MileContext);
gdh
2020-04-30