据我所知,当父组件
state
或
props
但我不知道反之亦然。
这是一个密码。
usePromise.js(定制挂钩)
import { useEffect, useReducer } from 'react';
const reducer = (state, action) => {
switch (action.type) {
case 'RESOLVED':
return { ...state, resolved: action.diff };
case 'LOADING':
return { ...state, loading: action.diff };
case 'ERROR':
return { ...state, resolved: action.diff };
default:
return state;
}
};
export default function usePromise(promiseCreator, deps = []) {
const [state, dispatch] = useReducer(reducer, {
resolved: null,
loading: false,
error: null
});
const process = async () => {
dispatch({ type: 'LOADING', diff: true });
try {
const result = await promiseCreator();
dispatch({ type: 'RESOLVED', diff: result });
} catch (e) {
dispatch({ type: 'ERROR', diff: e });
}
dispatch({ type: 'LOADING', diff: false });
};
useEffect(() => {
process();
}, deps);
return state;
}
import React from 'react';
import usePromise from './usePromise';
const wait = () => {
return new Promise(resolve =>
setTimeout(() => resolve('Hello hooks!'), 3000)
);
};
const UsePromiseSample = () => {
const { resolved, loading, error } = usePromise(wait);
console.log('test')
if (loading) return <div>loading...</div>;
if (error) return <div>error happened!</div>;
if (!resolved) return null;
return <div>{resolved}</div>;
};
export default UsePromiseSample;
你可以看到上面的代码,孩子(
usePromise.js
但似乎父母(
usePromiseSample.js
)由于测试记录了四次,所以也被重新渲染了四次。
我怎样才能容易地理解这种情况?