自定义钩子错误:只能在函数组件的主体中调用钩子

时间:2019-10-02 20:04:47

标签: reactjs typescript react-hooks

我知道在整个SO上都有这个问题的答案,但是我已经仔细研究了它们,并且尽我所能,我遵守规则,但仍然会出错。

enter image description here

static void Main(string[] args)
{
    DateTime dt = DateTime.Parse("2019-02-10 23:54:23");

    var interval = TimeSpan.FromMinutes(15);

     DateTime last = NextTime(dt, interval);

     Console.WriteLine(last);

    }

    private static DateTime NextTime(DateTime value, TimeSpan interval)
    {
        var temp = value.Add(new TimeSpan(interval.Ticks / 2));
        var time = new TimeSpan((temp.TimeOfDay.Ticks / interval.Ticks) * interval.Ticks);

        return value.Date.Add(time);
    }

和useSelector函数

const App: React.FC = () => {
  const count = useSelector<number>("counter", state => {
    const counter = state.get("counter");
    if (counter) {
      return counter.pipe(scan(total => total + 1)) as BehaviorSubject<number>;
    }
  });
  const dispatch = useDispatcher();
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>Counter : {count}</p>
        <button
          onClick={() => {
            dispatch.next({ type: Increment });
          }}
        >
          CLICK ME
        </button>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
};

Packge.json

mport { Selector, selectFromStore } from "../rxflux";
import { useState, useContext } from "react";
import {FluxContext} from "./FluxContext";

export function useSelector<T>(from: string, selector: Selector<T>) {
  const context = useContext(FluxContext);
  const [selectedState, setSelectedState] = useState();
  if (context) {
    const { store, storeMap } = context;
    const selection$ = selectFromStore(store, storeMap, from, selector)
    if(!selection$) {
      throw "Nothing returned from selector";
    }
    selection$.subscribe(v => setSelectedState(v));
    return selectedState;
  }

  throw "Context not registerd. Did your forget to use a Provider?";
}

0 个答案:

没有答案