我注意到,每当我访问路线时,当我使用 时<Link>,页面会自动滚动到底部,我有点困惑,因为它正在工作,我得到了页面,但它通过这种行为自动滚动到底部。
这是路由器:
import {Link,Routes,Route,Navigate} from 'react-router'
const App = () => {
const user=true
return <div>
<Routes>
<Route exact path='/' element={<Home/>} />
<Route exact path="/products/:category" element={ <ShoppingCat/>}/>
<Route exact path="/product/:id" element={ <ProductView/>}/>
<Route exact path="/cart" element={ <Cart/>}/>
<Route exact path="/login" element={user?<Navigate to='/'/>: <Login/>}/>
<Route exact path="/register" element={ user? <Navigate to='/'/> :<Register/>}/>
</Routes>
Run Code Online (Sandbox Code Playgroud)
这是访问路线的按钮<ProductView/>:
<Link to={`/product/${product._id}`}>
<button className='btn-4'>View </button>
</Link>
Run Code Online (Sandbox Code Playgroud) 我有一个基本的增量应用程序与以下代码反应。将函数传递到第一个按钮可以正常工作,但是将其传递到返回完全相同按钮的
handleClick子组件会出现错误: 。为什么它适用于第一个按钮,但不适用于子组件按钮,如何修复?提前致谢。IcrementButtonReact: Expected `onClick` listener to be a function, instead got a value of `object
import { useState } from "react";
import "./styles.css";
const IncrementButton = (handleClick) => {
return (
<button onClick={handleClick}>+</button>
)
}
export default function App() {
const [num, setNum] = useState(0)
const handleClick = (e) => {
e.preventDefault()
console.log('clicked')
setNum(prev => prev += 1)
}
return (
<div className="App">
<div>{num}</div>
<button onClick={handleClick}>+</button>
<IncrementButton handleClick={handleClick} />
</div>
);
}
Run Code Online (Sandbox Code Playgroud) 我通过对象传递用户对象,useNavigation例如:
let navigate = useNavigate();
const showUser = (user: UserProp): void => {
navigate('view', { state: user });
}
Run Code Online (Sandbox Code Playgroud)
一旦我登陆到该view组件,我就会尝试从该位置获取值。但出现错误。这是代码:
interface locationProps {
state: { user: UserProp }
}
export default function UserView() {
const { state } = useLocation<locationProps>();
return (
<h1>{state && state.user.name}</h1>
)
}
Run Code Online (Sandbox Code Playgroud)
出现错误为interface locationProps, Expected 0 type arguments, but got 1.
我有一个上下文,我将其导入到我的功能组件中:
import { TaskContexts } from "../../../contexts";
Run Code Online (Sandbox Code Playgroud)
上下文存储数据和函数。
数据来自上下文并显示在站点上。
const {
editTodo,
setEditID,
toggleTodoCompletion,
editID,
editTodoHandler,
removeTodo,
state,
text,
isEditError,
} = useContext(TaskContexts);
Run Code Online (Sandbox Code Playgroud)
但!
<button onClick={() => editTodo(todo.id)}>
<img src={editIcon} alt="edit button"></img>
</button>
Run Code Online (Sandbox Code Playgroud)
当我尝试调用 editTodo 函数时,它失败并出现以下错误:
Uncaught TypeError: editTodo is not a function
Run Code Online (Sandbox Code Playgroud)
如何修复这个错误?
UPD。
完整组件代码
import React, { useState } from 'react';
import ACTION_TYPES from '../ToDo/reducer/actionTypes';
import RenderedTable from './RenderedTable';
import styles from './TaskList.module.scss';
import allIcon from '../../icons/all.svg';
import completedIcon from '../../icons/completed.svg';
import notCompletedIcon from '../../icons/notCompleted.svg';
import mona from …Run Code Online (Sandbox Code Playgroud) 所以我想了解一下,React contexts但我有点困惑。从它的文档:
Context 提供了一种通过组件树传递数据的方法,而无需在每个级别手动向下传递 props。
所以这意味着我可以将应用程序的整个状态设为全局,并且可以从任何子组件更新它,对吧?但是我对如何使用它感到困惑。我有一个小应用程序,可以根据用户的输入向用户显示登录、注册或登录屏幕。我期望以下任何组件都应该能够更改存储在上下文中的全局对象的值,但我不确定如何使用它(提到不确定的函数todos)
// context
const MyAppSettings = React.createContext(
{
userId:null,
enableMarketing:false,
theme:"light"
}
)
Run Code Online (Sandbox Code Playgroud)
//ui components(having access to local state as well as global context
function SettingsUI({onThemeChange,onConsentChange}){
let settings = useContext(MyAppSettings)
return(
<div>
<button onClick={e=>onThemeChange()}>Change Theme to {settings.theme==="light"?"dark":"light"}</button>
<br/>
<button onClick={e=>onConsentChange()}> {settings.enableMarketing?"withdraw consent for marketing emails":"give consent for marketing emails"}</button>
</div>
)
}
function Auth({onAuthClick}){
let settings = useContext(MyAppSettings)
let textColor = settings.theme==="light" ? "black" : "white"
let bg = settings.theme==="light"?"white": "brown" …Run Code Online (Sandbox Code Playgroud) 我收到这个警告:
react-dom.development.js:86 警告:
reset标签上的 prop 值无效。要么将其从元素中删除,要么传递一个字符串或数字值以将其保留在 DOM 中。详情请参见https://reactjs.org/link/attribute-behavior
这来自我的自定义挂钩:
import { useState } from 'react'
export const useField = (type) => {
const [value, setValue] = useState('')
const onChange = (event) => {
setValue(event.target.value)
}
const reset = () => {
setValue('')
}
return {
type,
value,
onChange,
reset
}
}
Run Code Online (Sandbox Code Playgroud)
该钩子在组件中使用:
const CreateNew = (props) => {
const content = useField('text')
const author = useField('text')
const info = useField('text')
const navigate = useNavigate()
const handleSubmit = (e) …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用过滤器方法从数组中删除一个项目,如下所示:
removeDisplate: (state, action: PayloadAction<string>) => {
console.log(action.payload);
state.map((item) => {
console.log(item.name);
});
state.filter((item) => item.name !== action.payload);
},
Run Code Online (Sandbox Code Playgroud)
并从我的前端调用它,如下所示:
{cart.map((displate, index) => {
return (
<Card
sx={{
minHeight: "150px",
display: "flex",
padding: "10px",
gap: "10px",
backgroundColor: "black",
margin: "10px",
position: "relative",
}}
key={index}
>
<CloseIcon
sx={{
position: "absolute",
top: "10px",
right: "10px",
color: "red",
cursor: "pointer",
}}
onClick={() => handleRemoveDisplate(displate.name)}
/>
</Card>
);
})}
Run Code Online (Sandbox Code Playgroud)
状态中的有效负载和项目名称都与控制台日志相同,但它仍然没有从数组中删除它,有什么想法吗?
我使用 next.js 作为前端。我想从 localStorage 获取用户,但由于 next.js 是服务器端渲染,我无法获取 localStorage。我应该怎么做才能获得 localStorage?
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import authService from "./authService";
const getUserfromLocalStorage = localStorage.getItem("user")
? JSON.parse(localStorage.getItem("user"))
: null;
const initialState = {
user: getUserfromLocalStorage,
isError: false,
isLoading: false,
isSuccess: false,
message: "",
};
export const login = createAsyncThunk('auth/login', async (user, thunkAPI) => {
try {
return await authService.login(user);
} catch (error) {
return thunkAPI.rejectWithValue(error);
}
});
export const authSlice = createSlice({
name: "auth",
initialState,
reducers: {},
extraReducers: (builder) => { …Run Code Online (Sandbox Code Playgroud) 我正在使用 next.js 开发一个博客网站。我有一个主页,它是一个服务器组件,但现在我希望它更改为客户端组件,以便我可以使其具有交互性(集成分页)。
但是,当我将代码转换为客户端组件时,它开始给我带来问题,例如浏览器窗口在打开 localhost 时似乎有时会卡住。还有api请求getPosts方法没有通过 React 的 useState 的 setState 函数进行存储。
下面给出的是主页的先前服务器组件 -
import { getCategoryPosts, getPosts } from '@/services'
import styles from '../../app/page.module.scss'
import PostCard from './PostCard'
type Props = { categorySlug?: string }
async function HomePagePosts({ categorySlug = '' }: Props) {
const { postsContainer } = styles
let posts
if (!categorySlug) {
posts = await getPosts()
} else {
posts = await getCategoryPosts(categorySlug)
}
return (
<section className={postsContainer}>
{posts.map((post) => (
<PostCard post={post} key={post.title}></PostCard> …Run Code Online (Sandbox Code Playgroud) 我使用“react-redux”:“^ 9.0.4”,“react-router-dom”:“^ 6.21.1”,“react-scripts”:“5.0.1”,“redux”:“^ 5.0。 0", "redux-thunk": "^3.1.0" 我想使用 React-Redux 在 React.js 中使用中间件创建登录,这是我的代码。
// src/middleware/store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const guard = createStore(rootReducer, applyMiddleware(thunk));
export default guard;
Run Code Online (Sandbox Code Playgroud)
// src/middleware/actions.js
import axios from 'axios';
export const login = (username, password, history) => async (dispatch) => {
try {
const response = await axios.post('https://xxx-api.xxx-xxxxxxx.com/users/login', {
username,
password,
});
dispatch({
type: 'LOGIN_SUCCESS',
payload: {
user: response.data.user,
},
});
localStorage.setItem('token', response.data.data.token);
history.push('/admin/dashboard');
} catch …Run Code Online (Sandbox Code Playgroud) reactjs ×10
javascript ×7
next.js ×2
react-hooks ×2
react-router ×2
typescript ×2
html ×1
material-ui ×1
react-redux ×1
redux ×1
redux-thunk ×1
use-context ×1