Commit 3e7cf103 by 姜雷

优化context的使用

parent b48daa1f
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Switch, Route } from 'react-router-dom'; import { Switch, Route } from 'react-router-dom';
import UserInfoContext, { initUserinfo } from '../context/userinfo-context'; import { UserProvider } from '../context/userinfo-context';
import NavBar from '../components/NavBar'; import NavBar from '../components/NavBar';
import Index from './Index/Index'; import Index from './Index/Index';
...@@ -11,19 +11,10 @@ import BindEquipment from './BindEquipment'; ...@@ -11,19 +11,10 @@ import BindEquipment from './BindEquipment';
import NoMatch from './NoMatch'; import NoMatch from './NoMatch';
function App() { function App() {
const [userinfo, setUserinfo] = useState(initUserinfo);
const [title, setTitle] = useState('多彩运维'); const [title, setTitle] = useState('多彩运维');
return ( return (
<div className='App'> <div className='App'>
<UserInfoContext.Provider <UserProvider>
value={{
userinfo: userinfo,
updateUserInfo: val =>
setUserinfo({
...userinfo,
...val,
}),
}}>
<Route render={props => <NavBar {...props} title={title} />} /> <Route render={props => <NavBar {...props} title={title} />} />
<Switch> <Switch>
<Route <Route
...@@ -49,7 +40,7 @@ function App() { ...@@ -49,7 +40,7 @@ function App() {
/> />
<Route component={NoMatch} /> <Route component={NoMatch} />
</Switch> </Switch>
</UserInfoContext.Provider> </UserProvider>
</div> </div>
); );
} }
......
...@@ -21,7 +21,6 @@ export class Index extends React.Component { ...@@ -21,7 +21,6 @@ export class Index extends React.Component {
} }
componentWillMount() { componentWillMount() {
console.log(this.props);
const { setTitle, updateUserInfo } = this.props; const { setTitle, updateUserInfo } = this.props;
setTitle('登陆'); setTitle('登陆');
const { code } = this.props; const { code } = this.props;
......
import React from 'react'; import React, { createContext, useState } from 'react';
function is_weixn() { function is_weixn() {
var ua = navigator.userAgent.toLowerCase(); var ua = navigator.userAgent.toLowerCase();
...@@ -21,9 +21,24 @@ export const initUserinfo = { ...@@ -21,9 +21,24 @@ export const initUserinfo = {
}, },
}; };
export const UserContext = React.createContext({ export const UserContext = createContext();
userinfo: initUserinfo,
updateUserInfo: () => {}, export const UserProvider = props => {
}); const [userinfo, setUserinfo] = useState(initUserinfo);
return (
<UserContext.Provider
value={{
userinfo: userinfo,
updateUserInfo: val =>
setUserinfo({
...userinfo,
...val,
}),
}}>
{props.children}
</UserContext.Provider>
);
};
export default UserContext; export default UserContext;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment