我想在state数组的末尾添加一个元素,这是正确的方法吗?
this.state.arrayvar.push(newelement);
this.setState({arrayvar:this.state.arrayvar});
Run Code Online (Sandbox Code Playgroud)
我担心原地修改阵列push可能会造成麻烦 - 这样安全吗?
制作阵列副本的替代方案,setState这看起来很浪费.
我正在阅读reactjs文档的Forms部分,并尝试使用此代码来演示用法(JSBIN).onChange
var React= require('react');
var ControlledForm= React.createClass({
getInitialState: function() {
return {
value: "initial value"
};
},
handleChange: function(event) {
console.log(this.state.value);
this.setState({value: event.target.value});
console.log(this.state.value);
},
render: function() {
return (
<input type="text" value={this.state.value} onChange={this.handleChange}/>
);
}
});
React.render(
<ControlledForm/>,
document.getElementById('mount')
);
Run Code Online (Sandbox Code Playgroud)
当我<input/>在浏览器中更新值时,回调console.log内的第二个handleChange打印与value第一个相同console.log,为什么我看不到回调this.setState({value: event.target.value})范围内的结果handleChange?
当react组件状态发生变化时,将调用render方法.因此,对于任何状态更改,可以在呈现方法主体中执行操作.那么setState回调是否有特定的用例?
我想问一下当我做onclick事件时为什么我的状态没有改变.我刚才搜索过我需要在构造函数中绑定onclick函数,但状态仍未更新.这是我的代码:
import React from 'react';
import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import BoardAddModal from 'components/board/BoardAddModal.jsx';
import style from 'styles/boarditem.css';
class BoardAdd extends React.Component {
constructor(props){
super(props);
this.state = {
boardAddModalShow: false
}
this.openAddBoardModal = this.openAddBoardModal.bind(this);
}
openAddBoardModal(){
this.setState({ boardAddModalShow: true });
// After setting a new state it still return a false value
console.log(this.state.boardAddModalShow);
}
render() {
return (
<Col lg={3}>
<a href="javascript:;" className={style.boardItemAdd} onClick={this.openAddBoardModal}>
<div className={[style.boardItemContainer,style.boardItemGray].join(' ')}>
Create New Board
</div>
</a>
</Col> …Run Code Online (Sandbox Code Playgroud) 据我所知,React教程和文档毫不含糊地警告说,状态不应该直接变异,并且一切都应该通过setState.
我想明白为什么,确切地说,我不能直接改变状态,然后(在同一个函数中)调用this.setState({})只是为了触发render.
例如:以下代码似乎工作得很好:
const React = require('react');
const App = React.createClass({
getInitialState: function() {
return {
some: {
rather: {
deeply: {
embedded: {
stuff: 1
}}}}};
},
updateCounter: function () {
this.state.some.rather.deeply.embedded.stuff++;
this.setState({}); // just to trigger the render ...
},
render: function() {
return (
<div>
Counter value: {this.state.some.rather.deeply.embedded.stuff}
<br></br>
<button onClick={this.updateCounter}>inc</button>
</div>
);
}
});
export default App;
Run Code Online (Sandbox Code Playgroud)
我完全遵循以下约定,但我想进一步了解ReactJS如何实际运行,哪些可能出错或者是否与上述代码不是最佳的.
this.setState文档下的注释基本上确定了两个陷阱:
this.setState它可能会替换(覆盖?)你所做的突变.我不知道在上面的代码中会发生这种情况.setState …过去,我们曾明确警告过调用setState({myProperty})是异步的,并且this.state.myProperty直到回调或下一个render()方法才有效。
使用useState,如何在显式更新状态后获取状态的值?
钩子如何工作?据我所知,setter函数useState不接受回调,例如
const [value, setValue] = useState(0);
setValue(42, () => console.log('hi callback');
Run Code Online (Sandbox Code Playgroud)
不会导致回调运行。
在旧世界中,我的另一种解决方法是(e.g. this.otherProperty = 42)在类上挂一个实例变量,但这在这里不起作用,因为没有函数实例可以重用(this在严格模式下不可以)。
更新的问题:
如果我在滚动之前在输入字段中输入某些内容,则expanded道具将设置为 true - 正确
如果我向下滚动 - 展开设置为 false - 正确
如果我现在在输入字段中输入expanded内容仍然是false- 我希望再次expanded设置为true。
代码:
export default () => {
const [expanded, setExpanded] = useState(true)
let searchInput = React.createRef()
let scrollTopValue = 0;
function handleSearchInput() {
console.log(Boolean(searchInput.current.value.length))
setExpanded(Boolean(searchInput.current.value.length)) // first time true, don't get re triggered
}
useEffect(() => {
window.addEventListener('scroll', handleScroll)
return () => window.removeEventListener('scroll', handleScroll)
}, []);
function handleScroll() {
setExpanded(scrollTopValue > document.documentElement.scrollTop)
scrollTopValue = document.documentElement.scrollTop
}
return ( …Run Code Online (Sandbox Code Playgroud) React钩子介绍了useState用于设置组件状态的方法。但是我如何使用钩子来代替如下代码的回调:
setState(
{ name: "Michael" },
() => console.log(this.state)
);
Run Code Online (Sandbox Code Playgroud)
我想在状态更新后做一些事情。
我知道我可以useEffect用来做其他事情,但是我必须检查状态以前的值,这需要一个位代码。我正在寻找可以与useState钩子一起使用的简单解决方案。
我正在创建一个 DatePicker 并使用 useState 钩子来管理它的可见性。在 div 单击时,我添加了更改值的事件侦听器,但它没有按我预期的那样工作。它仅在第一次起作用,因此初始值更改为 true,但在第二次和第三次单击时,此值保持为 true,并且 DatePicker 在单击时保持可见。
这是日期选择器
import React, { useState } from 'react';
import OutsideClickHandler from 'react-outside-click-handler';
import { renderInfo, getWeeksForMonth } from './utils';
import {
renderMonthAndYear,
handleBack,
handleNext,
weekdays,
} from '../../utils';
const DatePicker = ({
isOpen,
setIsOpen,
selected,
setSelected,
dayClick,
dayClass,
}) => {
const startDay = new Date().setHours(0, 0, 0, 0);
const [current, setCurrent] = useState(new Date(startDay));
const weeks = getWeeksForMonth(current.getMonth(), current.getFullYear());
function handleClick(date) {
if (date > startDay) {
setSelected(date); …Run Code Online (Sandbox Code Playgroud) 我在 React 中有各种函数,我需要使用 useState 更改状态,然后根据新状态是否满足某些条件执行一些操作。
当使用 prop="newpassword" 调用 handleChange 时,这会使用 useState 中的 setValues 方法来设置 newpassword 的值。然后使用正则表达式测试评估新密码,如果有效,则状态变量passwordIsValid 应设置为true。
const handleChange = prop => event => {
setValues({ ...values, [prop]: event.target.value })
if (prop === 'newpassword' && passwordValidation.test(values.newpassword)) {
setValues({ ...values, passwordisValid: true })
console.log(prop, values.passwordisValid)
} else {
console.log(prop, values.passwordisValid)
}
}
Run Code Online (Sandbox Code Playgroud)
状态总是落后一步 - 我知道这是因为 useState 是异步的,但我不知道如何使用 useEffect 来检查状态?对 hooks 很陌生,有人可以帮助我吗?