useState() 给我未定义的新状态变量(通知):
const Notifications = (props) => {
const [notifications, setNotifications] = useState(props.notifications);//notifications = undefined, props = {notifications: Array(0)}
useEffect(() => {
if (props.notifications) {
setNotifications(props.notifications);
}
}, [props.notifications]);
// do stuff....
Run Code Online (Sandbox Code Playgroud)
我期待通知[],然后随后setNotifications()在props.notifications更改时更新它。props.notification来自 redux 商店。我不知道这是否会改变任何东西,但我确实设置了一个初始状态。
const initialState = Immutable.fromJS({
notifications: [],
});
Run Code Online (Sandbox Code Playgroud)
不知道为什么我变得未定义...
编辑:摆脱了错字和测试代码
我正在尝试为我设置测试component App.js,将 acontext作为道具并返回一个提供者。问题是当我尝试测试它时,我传递给它的上下文总是解析为未定义。
我在组件中放置了一个控制台日志,并在创建上下文和创建组件(应该接收上下文作为参数)之间放置一个控制台日志。由于某种原因,这首先导致了组件中的 console.log。这可能就是为什么我得到上下文未定义的原因,因为它尚未初始化。
// Component/Provider
const App = (props) => {
const {children, context} = props;
const {data, dispatch} = useReducer(reducer);
console.log(context); //undefined and this console.log runs first
return <context.Provider value={useCallback(dispatch)}>{children}</context.Provider>
}
Run Code Online (Sandbox Code Playgroud)
在我的 test.js 中
import React, {useContext} from 'react';
import {render} from 'react-testing-library';
import {App} from './App';
const context = React.createContext();
function Provider(children) {
console.log(context); //Is correct but runs second
return <App Context={context}>{children}</App>;
}
const customRender = (ui, options) =>
render(ui, { wrapper: …Run Code Online (Sandbox Code Playgroud) 我正在测试一个react使用setTimeout. 问题是,即使它显然不是Jest,也setTimeout被调用了。setTimeout当鼠标悬停在组件上时,有一个用于从 ui 中删除某些内容,另一个用于暂停计时器。
我尝试添加一个console.log()where the setTimeoutis 并且从不调用控制台日志,这意味着没有调用应用程序中的 setTimeout 。
//app
const App = (props) => {
const [show, setShow] = useState(true);
const date = useRef(Date.now());
const remaining = useRef(props.duration);
let timeout;
useEffect(() => {
console.log('Should not run');
if (props.duration) {
timeout = setTimeout(() => {
setShow(false)
}, props.duration);
}
}, [props.duration]);
const pause = () => {
remaining.current -= Date.now() - date.current;
clearTimeout(timeout);
}
const play …Run Code Online (Sandbox Code Playgroud) react-hooks ×3
reactjs ×3
jestjs ×2
unit-testing ×2
javascript ×1
redux ×1
timer ×1
undefined ×1