调度不是一个函数useContext/useReducer React hooks



My Home.js组件似乎根本没有看到调度功能。你们知道为什么吗?我对 redux 中的 redux 样式状态管理有点陌生。

我不断收到错误"类型错误:调度不是一个函数">

应用.js

import React from 'react';
import { HashRouter, Route } from 'react-router-dom';
import Home from './pages/Home';
import Start from './pages/Start';
import Result from './pages/Result';
import RPSContextProvider from './contexts/RPSContext';
const App = () => {
return (
<HashRouter>
<RPSContextProvider>
<Route exact path="/" component={Home} />
<Route path="/start" component={Start} />
<Route path="/result" component={Result} />
</RPSContextProvider>
</HashRouter>
);
};
export default App;

首页.js

import React, { useRef, useContext } from 'react';
import { RPSContext } from '../contexts/RPSContext';
import './home.css';
const Home = (props) => {
const { state, dispatch } = useContext(RPSContext);
const playerNameEntry = useRef();
const handleClick = () => {
if (!isStringEmpty(playerNameEntry.current.value)) {
dispatch({ type: 'SET_NAME', state: playerNameEntry.current.value });
props.history.push({
pathname: '/start'
});
console.log(dispatch);
}
};
const isStringEmpty = (string) => string.trim().length === 0;
return (
<div className="app-container">
<h1>
You dare battle me at
<br />
Rock, Paper, Scissors?
<br />
You got no chance, kid!
</h1>
<p>What's your name, ya chancer?</p>
<input type="text" onKeyPress={(e) => handleKeyPress(e)} ref={playerNameEntry} />
<button onClick={handleClick}>Start</button>
</div>
);
};
export default Home;

RPSContext.js

import React, { createContext, useReducer } from 'react';
import { RPSReducer } from '../reducers/RPSReducer';
export const RPSContext = createContext();
const RPSContextProvider = (props) => {
const [ state, dispatch ] = useReducer(RPSReducer, { playerName: '' });
return <RPSContext.Provider value={{ state, dispatch }}>{props.children}</RPSContext.Provider>;
};
export default RPSContextProvider;

RPSReducer.js

export const RPSReducer = (state, action) => {
switch (action.type) {
case 'SET_NAME':
return { playerName: action };
default:
throw new Error();
}
};

基本上作为第一步,我只想设置条目的名称。我知道这是相当多的代码,只是为了我正在做的事情,但只是想尝试useReducer和useContext,这样我就可以在React中学习所有这些新东西。

我通过添加解决了问题

switch (action.type) {
case 'SET_NAME':
return { ...state, playerName: action.payload }

在我的减速器和 Home 中.js将我在那里的状态键更改为有效负载。不能 100% 确定它是否具有相同的名称会影响任何事情,但它命名为有效载荷要不那么令人困惑。

const handleClick = () => {
if (!isStringEmpty(playerNameEntry.current.value)) {
dispatch({ type: 'SET_NAME', payload: playerNameEntry.current.value });

使用 AppContext.Provider 传递状态和调度包装整个应用程序,如下所示

<AppContext.Provider value={{ state, dispatch }}>
<div className="App">
<Compo />
</div>
</AppContext.Provider>

相关内容

  • 没有找到相关文章

最新更新