从子组件为 React 上下文添加价值
Posted
技术标签:
【中文标题】从子组件为 React 上下文添加价值【英文标题】:Add value to React context from child components 【发布时间】:2019-11-23 10:26:36 【问题描述】:我正在尝试在我的 React Native 应用程序中使用 React 上下文作为状态管理器。
这是上下文:
import React, createContext, useState, useEffect from "react";
import axios from "axios";
export const GlobalContext = createContext();
export const Provider = ( children ) =>
const [tracksList, setTracksList] = useState([
track_list: []
]);
useEffect(() =>
axios
.get(
`https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/chart.tracks.get?page=1&page_size=10&country=us&f_has_lyrics=1&apikey=$
process.env.REACT_APP_MM_KEY
`
)
.then(res =>
setTracksList([
track_list: res.data.message.body.track_list
]);
)
.catch(err => console.log(err));
, []);
return (
<GlobalContext.Provider value=[tracksList, setTracksList]>
children
</GlobalContext.Provider>
);
;
export const Consumer = GlobalContext.Consumer;
子组件。在这里,我想进行 API 调用以获取用户并将此用户字段设置为全局上下文。我可以从消费者那里获取上下文值,但是如何设置新的呢?
import React, useContext from "react";
import GlobalContext from "../../context/context";
const Demo = () =>
const contextValue = useContext(GlobalContext);
console.log(contextValue, "Context outside from JSX");
return <div>Content</div>;
;
export default Demo;
那么,是否可以从每个子组件中为 React 上下文添加新值,就像在 Redux 中一样?提前致谢!
【问题讨论】:
【参考方案1】:您可以使用useReducer
效果来实现 Redux 减速器:
// Create context
export const ApiContext = React.createContext();
// Create some reducer function
const reducer = (state, action) =>
if (action.type === 'some action name')
return
...state,
report: action.payload,
;
return state;
;
// Overwrite a context provider
const Provider = ( children ) =>
const [state, dispatch] = React.useReducer(reducer, );
return (
<ApiContext.Provider
value=
...state,
dispatch,
>
children
</ApiContext.Provider>
);
;
那么你可以在组件中使用如下:
const Component = () =>
const dispatch, report = React.useContext(ApiContext);
React.useEffect(() =>
const asyncPost = async () =>
const response = await fetch('some endpoint',
method: 'POST',
);
const payload = await response.json();
// This will call a reducer action and update a state
dispatch(
type: 'some action name',
payload,
);
, []);
...
;
所以当Component
被挂载时,状态将是一个空对象。然后当您使用some action name
操作更新状态时,状态变为 report: some data from fetch
。
【讨论】:
以上是关于从子组件为 React 上下文添加价值的主要内容,如果未能解决你的问题,请参考以下文章