如何更改此类基 Context API 以到达 Hook,而不更改已使用它的其他组件?我是个新手, react 迟钝,花了一晚上的时间,结果被卡住了。
实际的代码比这更多,但为了简单起见,我试图删除一些代码:
import React, { createContext, Component } from 'react'
const MainContext = createContext();
class MainContextProvider extends Component {
state = {
isLogin : false,
loginData : [],
spinner : false
}
handleUserLogin = (res) => {
this.setState({
...this.state,
isLogin : res.isLogin,
loginData : res.data
})
}
showSpinner = (status) => {
this.setState({
...this.state,
spinner : status
})
}
render() {
console.log(this.state)
return (
<MainContext.Provider value = {{
...this.state,
showSpinner : this.showSpinner,
handleUserLogin : this.handleUserLogin,
}}>
{this.props.children}
</MainContext.Provider>
);
}
}
const MainContextConsumer = MainContext.Consumer;
export {MainContextProvider, MainContextConsumer, MainContext};
我用这个 MainContextProvider 包装了 index.js,这样所有组件都可以使用状态或使用方法。
最佳答案
以下是如何将 context
与钩子(Hook)结合使用并保持与您已有的 API 相同的 API:
import React, { createContext, useContext, useState } from "react";
import "./style.css";
// Define your context, this is the same
const MainContext = createContext();
function Provider({ children }) {
// Define some state to hold the data
let [state, setState] = useState({
isLogin: false,
loginData: [],
spinner: false
});
// Define a few functions that change the state
let handleUserLogin = res => {
setState(s => ({
...s,
isLogin: res.isLogin,
loginData: res.data
}));
};
// Define a few functions that change the state
let showSpinner = status => {
setState(s => ({ ...s, spinner: status }));
};
// Pass the `state` and `functions` to the context value
return (
<MainContext.Provider
value={{ ...state, handleUserLogin, showSpinner }}
>
{children}
</MainContext.Provider>
);
}
function Stuff() {
// Inside your component use the context with `useContext` hook
let { showSpinner, handleUserLogin, ...state } = useContext(MainContext);
return (
<div>
<div>
<code>{JSON.stringify(state, null, 2)}</code>
</div>
<button onClick={() => showSpinner(Math.random())}>
Show Spinner
</button>
</div>
);
}
export default function App() {
return (
<Provider>
<Stuff />
</Provider>
);
}
关于javascript - 将 React Context API 类转换为 Hook 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64562934/