我正在尝试使用 redux 值来使用 useState 设置 React 组件的初始状态。当我尝试设置 setIsStar 的状态时,它说 currentChannelName 为 null。我怎样才能避免这种情况?或者还有其他方法吗
const currentChannel = useSelector(state => state.channel.currentChannel);
const currentChannelName = currentChannel.name;
const [isStar, setIsStar] = useState({
[currentChannelName]: true
});
Run Code Online (Sandbox Code Playgroud) 我正在 React 中进行登录/注册,并使用 firebase auth 进行身份验证。当用户登录时,我想在根路径或应用程序组件上重定向用户。但我陷入了无限循环,这给了我这个错误(限制导航以防止浏览器挂起。)
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import "semantic-ui-css/semantic.min.css";
import App from "./App";
import firebase from "firebase";
import { BrowserRouter, Switch, Route, withRouter } from "react-
router-dom";
import Login from "./components/Login";
import Register from "./components/Register";
const Root = props => {
useEffect(() => {
firebase.auth().onAuthStateChanged(user => {
if (user) {
props.history.push("/");
}
});
});
return (
<Switch>
<Route exact path="/" component={App} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} /> …Run Code Online (Sandbox Code Playgroud) 我已经开始使用新的 React-Hook-form 库,并希望在 Change 而不是 Submit 上提交我的输入字段。另外,我计划使用 Lodash 的 debounce 来避免重新渲染
这是我迄今为止尝试过的:
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";
import "./styles.css";
export default function App() {
const { register, handleSubmit, setValue } = useForm();
useEffect(() => {
register({ name: "firstName" }, { required: true });
}, [register]);
return (
<form>
<input
name="firstName"
onChange={(e) => {
setValue("firstName", e.target.value);
handleSubmit((data) => console.log("data", data));
}}
/>
</form>
);
}
const rootElement = document.getElementById("root"); …Run Code Online (Sandbox Code Playgroud) 我刚刚开始在 React 中使用 typescript。我尝试将它与 React useReducer 挂钩一起使用,但由于一个奇怪的错误而陷入困境。
这是我的代码:
export interface ContractObj {
company: string;
negotiationRenewalDate: string;
periodEnd: string;
periodStart: string;
scheduleForRenewal: boolean;
contractId: string;
}
type State = {
loading: boolean;
error: boolean;
contractsData: ContractObj[];
};
type Action =
| { type: 'FETCH_SUCCESS'; payload: ContractObj[] }
| { type: 'FETCH_ERROR'; payload: null };
const initialState: State = {
loading: true,
error: false,
contractsData: []
};
const reducer = (state: State, action: Action) => {
switch (action.type) {
case 'FETCH_SUCCESS':
return …Run Code Online (Sandbox Code Playgroud)