我的Home.js组件似乎根本看不到调度功能。你们知道为什么吗?我对redux中的redux样式状态管理有所了解。
我不断收到错误消息“ TypeError:调度不是函数”
App.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;
Home.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中学习所有这些新东西。
答案 0 :(得分:0)
我通过添加
解决了该问题 switch (action.type) {
case 'SET_NAME':
return { ...state, playerName: action.payload }
在我的reducer中,以及在Home.js中,将其中的状态键更改为有效负载。不确定100%是否具有相同的名称会产生任何影响,但将其命名为有效负载却不那么容易了。
const handleClick = () => {
if (!isStringEmpty(playerNameEntry.current.value)) {
dispatch({ type: 'SET_NAME', payload: playerNameEntry.current.value });
答案 1 :(得分:0)
使用AppContext.Provider封装整个App,并传递状态和调度,如下所示
private fun registerNetworkCallback() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(callback)
} else {
// Old way to check network connection
}
}
override fun onStop() {
unRegisterNetworkCallback()
super.onStop()
}
private fun unRegisterNetworkCallback() {
connectivityManager.unregisterNetworkCallback(callback)
}