Open zhouchao941105 opened 3 years ago
题一
function useOnline(id) {
const [isOnline, setIsOnline] = React.useState(false)
React.useEffect(() => {
// 模拟/api/online返回
window.fetch('http://api2.jirengu.com/getWeather.php?city=%E5%8C%97%E4%BA%AC&id=' + id, {
method: 'get',
}).then(data => {
setIsOnline(data.ok)
})
})
return isOnline
}
题二
function useReducer(reducer, initialState) {
const [state, setState] = React.useState(initialState)
function dispatch(action) {
const nextState = reducer(state, action)
setState(nextState)
}
return [state, dispatch]
}
function fruitsReducer(state, action) {
switch (action.type) {
case 'add':
return [
...state,
action.text
]
// ... other actions ...
default:
return state
}
}
const Main = () => {
const [fruits, dispatch] = useReducer(fruitsReducer, [])
// 初始化
useEffect(() => {
dispatch({
type: 'add',
text: '苹果',
})
}, [])
}
const getOnlineStatus = id => {
const [status, setStatus] = useState()
useEffect(() => {
//
fetch('/api/online?id' + id).then(res => {
if (!res) return;
setStatus(res)
})
}, [id])
return status
}
const _useReducer = (reducer, initialState) => {
const [state, setState] = useState(initialState)
const dispatch = useCallback((action) => {
const nextState = reducer(state, action)
setState(nextState)
}, [state, reducer])
return [state, dispatch]
}
const getOnlineStatus = id => {
const [onlineStatus, setOnlineStatus] = useState()
useEffect(() => {
//
fetch('/api/online?id=${id}').then(res => {
setOnlineStatus(res.data)
})
}, [id])
return onlineStatus
}
function useOnline({ id }) {
const [isOnline, setIsOnline] = useState(false)
useEffect(() => {
API.fetch({ url: 'url', id }).then(res => {
setIsOnline(res.data)
})
})
return isOnline
}
/useMyReducer
function useMyReducer({reducer,initState }) {
const [state, setState] = useState(initState)
const dispath = useCallback( (params)=>{
setState(reducer(state,paramas))
},[reducer,state])
return [
state,
dispatch
]
}
/app
import useMyReducer from './useMyReducer'
function reducer (oldState,params) {
return oldState + params
}
function App() {
const [state,dispatch] = useMyReducer(reducer,1)
return <button onClick={()=>{dispatch(1)}}>
}
function useOnlone(id) {
const [online, setOnline] = useState(false)
useEffect(() => {
fetch(`/api/online/${id}`).then((res) => setOnline(Boolean(res)))
})
return online
}
/api/online
可返回这个id的在线状态,最终返回当前id的在线状态useState
实现一个简易版本的useReducer