我检索了存储useState在对象数组中的数据,然后将数据输出到表单字段中。现在我希望能够在我输入时更新字段(状态)。
我见过关于人们更新数组中属性状态的例子,但从来没有更新过对象数组中的状态,所以我不知道该怎么做。我已经将对象的索引传递给回调函数,但我不知道如何使用它更新状态。
// sample data structure
const datas = [
{
id: 1,
name: 'john',
gender: 'm'
}
{
id: 2,
name: 'mary',
gender: 'f'
}
]
const [datas, setDatas] = useState([]);
const updateFieldChanged = index => e => {
console.log('index: ' + index);
console.log('property name: '+ e.target.name);
setData() // ??
}
return (
<React.Fragment>
{datas.map((data, index) => {
<li key={data.name}>
<input type="text" name="name" value={data.name} onChange={updateFieldChanged(index)} />
</li>
})}
</React.Fragment>
)
Run Code Online (Sandbox Code Playgroud) 我正在尝试下面的useEffect示例:
useEffect(async () => {
try {
const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
}, []);Run Code Online (Sandbox Code Playgroud)
我在我的控制台中收到此警告.但我认为清理对于异步调用是可选的.我不知道为什么我会收到这个警告.链接沙箱的例子.https://codesandbox.io/s/24rj871r0p

使用React 16.8.6(在以前的版本16.8.3中很好),当我尝试防止在获取请求上发生无限循环时,出现此错误
./src/components/BusinessesList.js
Line 51: React Hook useEffect has a missing dependency: 'fetchBusinesses'.
Either include it or remove the dependency array react-hooks/exhaustive-deps
Run Code Online (Sandbox Code Playgroud)
我一直找不到停止无限循环的解决方案。我想远离使用useReducer()。我确实在https://github.com/facebook/react/issues/14920找到了这个讨论,在这里可能的解决方案是You can always // eslint-disable-next-line react-hooks/exhaustive-deps if you think you know what you're doing.我不确定自己在做什么,所以我还没有尝试实现它。
我有这个当前设置,React hook useEffect永远/无限循环连续运行,唯一的注释是useCallback()我不熟悉的。
我目前的使用方式useEffect()(类似于,我一开始只想运行一次componentDidMount())
useEffect(() => {
fetchBusinesses();
}, []);
Run Code Online (Sandbox Code Playgroud)
const fetchBusinesses = () => {
return fetch("theURL", {method: "GET"}
)
.then(res => normalizeResponseErrors(res))
.then(res => {
return res.json();
}) …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用React钩子解决一个简单的问题
const[personState,setPersonState]= useState({DefinedObject});
Run Code Online (Sandbox Code Playgroud)
具有以下依赖性。
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.0"
}
Run Code Online (Sandbox Code Playgroud)
但我仍然收到以下错误:
./src/App.js
第7行:
在函数“ app”中调用React Hook“ useState”,该函数既不是React函数组件也不是自定义的React Hook函数react-hooks / rules-of-hooks第39行: 未定义
“状态”搜索关键字以了解有关每个错误的更多信息。
我正在尝试新的React Hooks并且有一个带有计数器的Clock组件,它应该每秒都会增加.但是,该值不会超过一个.
function Clock() {
const [time, setTime] = React.useState(0);
React.useEffect(() => {
const timer = window.setInterval(() => {
setTime(time + 1);
}, 1000);
return () => {
window.clearInterval(timer);
};
}, []);
return (
<div>Seconds: {time}</div>
);
}
ReactDOM.render(<Clock />, document.querySelector('#app'));Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>Run Code Online (Sandbox Code Playgroud)
我在使用useState钩子时遇到此错误.我有它的基本形式,查看反应文档作为参考,但我仍然得到这个错误.我已准备好面对掌心时刻......
export function Header() {
const [count, setCount] = useState(0)
return <span>header</span>
}
Run Code Online (Sandbox Code Playgroud) 我有这个组件:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default App;
Run Code Online (Sandbox Code Playgroud)
因为我想通过在我的安装中尝试新的React钩子提议,但我收到一个错误:react@16.8.1package.json
TypeError: dispatcher.useState is not a function
2 | import ReactDOM from "react-dom";
3 |
4 | function App() {
> 5 | const [count, …Run Code Online (Sandbox Code Playgroud) 我目前正在学习React中的钩子概念,并试图理解下面的例子.
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
上面的示例在处理程序函数参数本身上递增计数器.如果我想修改事件处理函数内的计数值怎么办?
考虑下面的例子
setCount = () => {
//how can I modify count value here. Not sure if I can use setState to modify its value
//also I want to modify other state values as well here. …Run Code Online (Sandbox Code Playgroud) 我想调用一个异步函数并获取我的 UseEffect 的结果。
我在网上找到的fetch api例子是直接在useEffect函数中制作的。如果我的 URL 发生变化,我必须修补我所有的提取。
当我尝试时,我收到一条错误消息。
这是我的代码。
async function getData(userId) {
const data = await axios.get(`http://url/api/data/${userId}`)
.then(promise => {
return promise.data;
})
.catch(e => {
console.error(e);
})
return data;
}
function blabla() {
const [data, setData] = useState(null);
useEffect(async () => {
setData(getData(1))
}, []);
return (
<div>
this is the {data["name"]}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
index.js:1375 警告:除了用于清理的函数之外,效果函数不得返回任何内容。看起来你写了 useEffect(async () => ...) 或者返回了一个 Promise。相反,在您的效果中编写异步函数并立即调用它:
useEffect(() => {
async function fetchData() {
// You can await here
const response = …Run Code Online (Sandbox Code Playgroud) React 抱怨下面的代码,说它 useEffect 被有条件地调用:
import React, { useEffect, useState } from 'react'
import VerifiedUserOutlined from '@material-ui/icons/VerifiedUserOutlined'
import withStyles from '@material-ui/core/styles/withStyles'
import firebase from '../firebase'
import { withRouter } from 'react-router-dom'
function Dashboard(props) {
const { classes } = props
const [quote, setQuote] = useState('')
if(!firebase.getCurrentUsername()) {
// not logged in
alert('Please login first')
props.history.replace('/login')
return null
}
useEffect(() => {
firebase.getCurrentUserQuote().then(setQuote)
})
return (
<main>
// some code here
</main>
)
async function logout() {
await firebase.logout()
props.history.push('/')
}
} …Run Code Online (Sandbox Code Playgroud)