小编Lea*_*ove的帖子

在 React 中有条件地执行 useContext

我希望有条件地调用 useContext。这是我的原始代码,它运行正确,但 tslint 失败。

调用useResourceScope的组件- 比如说Component1

import { useEffect } from 'react';

export function useSubscribeListItemStore(
  inputResources?: ResourceScope
) {
  const resources = inputResources || useResourceScope();
  const listItemStore = resources.consume(listItemStoreKey);
  
  useEffect(function subscribeListItemStore() {
    // do some logic
  }, []);
}
Run Code Online (Sandbox Code Playgroud)

定义useResourceScope的组件- 比如说Component2

import { createContext } from 'preact';
import { useContext } from 'preact/hooks';

export const ResourceScopeContext = createContext<ResourceScope | undefined>(undefined);

export function useResourceScope(): ResourceScope {
  const resources = useContext(ResourceScopeContext);
  if (!resources) {
    throw new Error( …
Run Code Online (Sandbox Code Playgroud)

reactjs preact react-hooks use-context createcontext

6
推荐指数
1
解决办法
5079
查看次数

使用 @types/history 中的 createBrowserHistory() 时出现 Tslint 错误

我正在我的 React 应用程序中导入@types/history并使用createBrowserHistory()它提供的功能。

我收到一个 tslint 错误,说

ERROR in C:/Users/eshan/my-website/src/App.tsx
ERROR in C:/Users/eshan/my-website/src/App.tsx(13,11):
typedef: expected variable-declaration: 'history' to have a typedef
Run Code Online (Sandbox Code Playgroud)

我确实环顾四周,但所有缓解这种情况的尝试似乎都是为了通过执行/* tslint:disable */. 我想添加类型支持,然后修复它。

import * as React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import './App.css';

class App extends React.Component {
  public render(): JSX.Element {
  const history = createBrowserHistory();

  return (
    <div className='App'>
      <Router history={history}>
        <Switch>
          <Route exact path='/' component={Landing}/>
          <Route exact path='/Home' component={Home}/> …
Run Code Online (Sandbox Code Playgroud)

typescript tslint

3
推荐指数
1
解决办法
3356
查看次数