我一直在这样做,但有些大学告诉我应该改用useEffectHook。问题是我没有看到这种方法的好处,而且我认为我的方法更简洁。
import React, { useState, useEffect } from "react";
const fetchTheApi = () =>
new Promise(res => setTimeout(() => res({ title: "Title fetched" }), 3000));
const UseEffectlessComponent = () => {
const [data, setData] = useState();
!data && fetchTheApi().then(newData => setData(newData));
return <h1>{data ? data.title : "No title"}</h1>;
};
const UseEffectComponent = () => {
const [data, setData] = useState();
useEffect(() => {
fetchTheApi().then(newData => setData(newData));
}, []);
return <h1>{data ? data.title : "No title"}</h1>;
};
const MyComponent …Run Code Online (Sandbox Code Playgroud) 我想在 React 渲染元素后立即滚动到元素中给定的水平位置。对于上下文,我使用 Next.js 进行服务器端渲染,因此useLayoutEffect不是一个选项。
export default function WideElement () {
const ref = useRef(null)
useEffect(function () {
ref.current.scrollLeft = 1000
}, [])
return (
<Container ref={ref}>
...
</Container>
)
}
Run Code Online (Sandbox Code Playgroud)
但是,上面的代码在页面加载时不会滚动。这里...代表一长串水平堆叠并溢出容器的子元素。
我注意到,如果我对滚动施加人为延迟,它似乎工作正常,并且Container立即向左滚动 1000 像素。
export default function WideElement () {
const ref = useRef(null)
useEffect(function () {
setTimeout(function() {
ref.current.scrollLeft = 1000
}, 1000)
}, [])
return (
<Container ref={ref}>
...
</Container>
)
}
Run Code Online (Sandbox Code Playgroud)
我想我可能是误会了useEffect。我错过了什么,我怎样才能做到这一点?
我有这个钩子,它在挂载上调用 redux 操作。所以我的猜测是应该执行一次。但事实并非如此。
useCategories.js
const useCategories = () => {
/*
Hook to call redux methods that will fetch the categories
of the exercises. Store it in redux store.
RETURN: loading, error, data
*/
const mainCategories = useSelector(state => state.categories.specialities);
const loading = useSelector(state => state.categories.loading);
const error = useSelector(state => state.categories.error);
const dispatch = useDispatch();
const onInitExercises = useCallback(
() => dispatch(actions.fetchCategories()),
[dispatch]
);
useEffect(() => {
console.log("[useCategories] --> UseEffect");
onInitExercises();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [onInitExercises]);
const data = …Run Code Online (Sandbox Code Playgroud) 嗨,我有一个场景,我需要在特定场景中使用 React_hooks 在反应钩子中设置新状态后替换 setState 回调。
当前代码是::
const ThemeOptions = () => {
const [previewType, setPreviewType] = useState("Desktop");
const [previewUrl, setPreviewUrl] = useState("");
const [layout, setLayout] = useState(null);
const [saving, setSaving] = useState(false);
const handleSave = (newdata) => {
setLayout(newdata);
setSaving(true);
axios
.put(window.urls.save, this.state.layout)
.then(
function(response) { // i want this to change in hooks
this.setState(
{
layout: response.data,
saving: false,
},
function() {
this.refs["preview"].refresh();
}
);
}.bind(this)
)
.catch(
function(error) {
console.log(error);
setSaving(false);
}.bind(this)
);
}
return (
<div>
<Router> …Run Code Online (Sandbox Code Playgroud) 我基本上正在学习 Jest,我必须为 useEffect() 钩子编写一个测试用例,该钩子基于 flag[counter] 进行渲染,并在内部检查字段是否存在 localStorage 值。
function sample(props) {
const counter = props;
const [displayIcon, setDisplayIcon] = useState(counter);
function isLocalstoragePresent() {
return localStorage.getItem("some_Id");
}
useEffect(() => {
if (isLocalstoragePresent()) {
setDisplayIcon(true);
} else {
setDisplayIcon(false);
}
}, [counter]);
export default sample;
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我编写测试用例/为内部调用 isLocalstoragePresent() 方法的 UseEffect 提供指导吗?提前致谢。
我正在使用 React Native 开发移动应用程序。在那里,我在导航到第二页时传递了一些内容。
所以,假设我的第一个屏幕有这样的东西。
export default function firstScreen(props) {
return(
//data is a custom object variable that may be changed.
<Button onPress={() => props.navigation.navigate('SecondScreen', { data: data } )} />
)
}
Run Code Online (Sandbox Code Playgroud)
在我的第二个屏幕上,假设有这样的东西......
export default function secondScreen(props) {
const { data } = props.navigation.state.params;
useEffect(() => {
console.log(data);
}, [data])
return(
//content
)
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,当data从第一个屏幕更改时,第二个屏幕不会监听该更改并data在控制台上打印变量的内容。
所以,我想知道,如何在React Native中监听导航状态的变化。
我正在使用 Promise 进行多次调用。
我要获取的 API 端点是:
看代码
export function getTeamsStats(league, team, type) {
return function(dispatch) {
const url = "https://www.api-football.com/demo/v2/statistics";
let dates = ["2019-08-30", "2019-09-30", "2019-10-30"];
const getAllData = (dates, i) => {
return Promise.allSettled(dates.map(x => url + '/' + 357 + '/' + 5 + '/' + x).map(fetchData));
}
const fetchData = (URL) => {
return axios
.get(URL)
.then(res => {
const {
matchsPlayed: { total: teamsTotalMatchsPlayed},
} = res.data.api.statistics.matchs;
const matchsPlayed = teamsTotalMatchsPlayed;
dispatch(receivedTeamsStat(matchsPlayed, type)); …Run Code Online (Sandbox Code Playgroud) 我是新来的反应。我已经阅读了 React 文档。我不知道为什么它不起作用。所以,我来到这里。
我正在尝试在反应中创建分页。下面是我的table组件。
const Table = (props) => {
const { description, itemCount, tableHeaders, items } = props;
const pageSize = 5;
const [currentPage, setCurrentPage] = useState(1);
function handlePageChange(page) {
setCurrentPage(page);
}
const registerations = paginate(items, currentPage, pageSize);
// HERE: registerations data is correct and then I pass it to TableBody component.
return (
<React.Fragment>
<TableDescription description={description} count={itemCount} />
<div className="bg-white block w-full md:table">
<TableHeader items={tableHeaders} />
<TableBody items={registerations} />
</div>
{/* Footer & Pagination */}
<div …Run Code Online (Sandbox Code Playgroud) 我想知道useEffect钩子清理函数何时在反应中被调用,它是在依赖项更改时调用还是在组件卸载时调用。
例如在我的组件中如果我有useEffect
useEffect(()=>{
return ()=>{
//clean up function code
} //clean up function
},[dependency])
Run Code Online (Sandbox Code Playgroud)
清理函数会在更改时调用dependency还是在组件卸载时调用。
我的导航栏上有 6 个链接(家庭、世界、政治、商业、技术、体育),我只希望“部分”参数成为这些值之一。如果输入“section”的其他值,则会显示“找不到页面”消息。
所有 6 个链接都工作正常。单击导航栏上的另一个链接时,useEffect 会重新运行。但是,如果我输入无效的部分参数,它首先显示“找不到页面”消息,然后我单击导航栏上的链接,useEffect 不会重新运行并且应用程序崩溃。
我无法弄清楚为什么 useEffect 不重新运行,我确实指定了 props.match.params.section 作为其依赖项。
const Headlines = (props) => {
useEffect(() => {
console.log(props.match.params.section);
props.getArticles(props.match.params.section === 'sports' ? 'sport' : props.match.params.section);
}, [props.match.params.section]);
if (props.match.params.section !== undefined &&
props.match.params.section !== 'world' &&
props.match.params.section !== 'politics' &&
props.match.params.section !== 'business' &&
props.match.params.section !== 'technology' &&
props.match.params.section !== 'sports') {
return (
<Container fluid>
<h1>The page cannot be found</h1>
</Container>
);
}
return (
props.news.loading ?
<Spinner/>
:
<Container fluid className={classes.headlines}>
{props.news.articles.map((article) => …Run Code Online (Sandbox Code Playgroud) use-effect ×10
reactjs ×9
react-hooks ×6
javascript ×5
use-state ×2
jestjs ×1
navigation ×1
promise ×1
react-native ×1
scroll ×1
setstate ×1
state ×1
unit-testing ×1