gpt4 book ai didi

reactjs - Dispatch 不是函数 useContext/useReducer React hooks

转载 作者:行者123 更新时间:2023-12-03 14:38:46 25 4
gpt4 key购买 nike

我的 Home.js 组件似乎根本看不到 dispatch 函数。大家知道为什么吗?我对 redux 中的 redux 样式状态管理内容有点陌生。

我不断收到错误“TypeError:dispatch is not a function”

应用程序.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 }

在我的 reducer 中,在 Home.js 中将我在那里的状态 key 更改为有效负载。不能 100% 确定它是否具有相同的名称会影响任何东西,但命名它的有效载荷要少得多。
    const handleClick = () => {
if (!isStringEmpty(playerNameEntry.current.value)) {
dispatch({ type: 'SET_NAME', payload: playerNameEntry.current.value });

关于reactjs - Dispatch 不是函数 useContext/useReducer React hooks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58125665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com