我想在state数组的末尾添加一个元素,这是正确的方法吗?
this.state.arrayvar.push(newelement);
this.setState({arrayvar:this.state.arrayvar});
Run Code Online (Sandbox Code Playgroud)
我担心原地修改阵列push可能会造成麻烦 - 这样安全吗?
制作阵列副本的替代方案,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) 我正在尝试学习钩子,而useState方法使我感到困惑。我正在将初始值分配给数组形式的状态。即使使用spread(...)或,useState中的set方法对我也不起作用without spread operator。我在另一台PC上制作了一个API,我正在调用它并提取要设置为状态的数据。
这是我的代码:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const StateSelector = () => {
const initialValue = [
{
category: "",
photo: "",
description: "",
id: 0,
name: "",
rating: 0
}
];
const [movies, setMovies] = useState(initialValue);
useEffect(() => {
(async function() {
try {
//const response = await fetch(
//`http://192.168.1.164:5000/movies/display`
//);
//const json = await response.json();
//const result = json.data.result;
const result = [
{
category: …Run Code Online (Sandbox Code Playgroud) 假设我有1000个项目的列表.我用React渲染它,像这样:
class Parent extends React.Component {
render() {
// this.state.list is a list of 1000 items
return <List list={this.state.list} />;
}
}
class List extends React.Component {
render() {
// here we're looping through this.props.list and creating 1000 new Items
var list = this.props.list.map(item => {
return <Item key={item.key} item={item} />;
});
return <div>{list}</div>;
}
}
class Item extends React.Component {
shouldComponentUpdate() {
// here I comparing old state/props with new
}
render() {
// some rendering here...
}
} …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个函数,它接受一个键和一个值,并更新类型化对象上相应的键值对。这是我所追求的一个基本示例。
type x = {
prop : number,
other : string
}
let dataToUpdate : x = {
prop: 1,
other: "string"
}
function updateKey(key : string, value : number | string) {
dataToUpdate[key] = value;
}
Run Code Online (Sandbox Code Playgroud)
我通过上述实现收到此错误。
元素隐式具有
'any'类型,因为 type 的表达式'string'不能用于索引 type'x'。'string'在类型上找不到带有类型参数的索引签名'x'。(7053)
更新我被介绍了XY Problem 的想法。下面是我所追求的实际实现。我正在尝试在 React 中创建一个上下文,该上下文返回一个函数,该函数允许您仅更新存储在上下文中的对象内的特定属性
export function StoreProvider(props: any) {
const [storeData, setStoreData] = useState<StoreData>(initProviderData);
function setStoreKeyValue(keyToUpdate: keyof StoreData[], valueToSet: boolean | string | number | …Run Code Online (Sandbox Code Playgroud) 下面的反应代码是错误的吗?
state={ foo: { bar: true } } // line 1
setState(state) // line 2
state.foo.bar = false // line 3
setState(state) // line 4
Run Code Online (Sandbox Code Playgroud)
如果是,为什么?
这表明它是错误的,但没有解释为什么?
我认为这并没有错,原因如下:
line 2 vdom1创建line 4 vdom2创建vdom1并vdom2进行比较如果是这种情况,那么 处state的突变line3不应对 处发生的情况产生任何影响line4。
换句话说:
这应该是等效的代码:
state={ foo: { bar: true } } // line 1
setState(state) // line 2
state={ foo: { bar: false } } // line …Run Code Online (Sandbox Code Playgroud) 我有一个简单的学生对象列表,其中包含姓名和状态分数.
他们的名字是必然的<b>{student.name}</b>,他们的分数是必然的
<input type="text" defaultValue={student.score}/>
Run Code Online (Sandbox Code Playgroud)
什么时候我想从这个列表中删除第一个学生并通过调用set state重新渲染组件
第二个学生的输入标签显示第一个学生的分数而不是自己的分数.为什么这会发生在我做错的地方?
这里是我的代码,这里是jsbin中的mycode
class App extends React.Component{
constructor(){
super();
this.state ={
students:[{name:"A",score:10},{name:"B",score:20},{name:"C",score:30}]
}
}
onDelete(index){
this.state.students.splice(index,1);
this.setState(this.state);
}
render(){
return(
<div>
{this.state.students.map((student,index)=>{
return(
<div key={index}>
<b>{student.name}</b> - <input type="text" defaultValue={student.score}/>
<button onClick={this.onDelete.bind(this,index)}>delete</button>
</div>
)
})}
</div>
)
}
}
ReactDOM.render(<App/>,document.getElementById("main"));
Run Code Online (Sandbox Code Playgroud) 我在 React useState 钩子上遇到了一些麻烦。我有一个带有复选框按钮的待办事项列表,我想将 'done' 属性更新为 'true',它的 id 与 'clicked' 复选框按钮的 id 相同。如果我 console.log 我的 'toggleDone' 函数它返回正确的 id。但我不知道如何更新正确的属性。
当前状态:
const App = () => {
const [state, setState] = useState({
todos:
[
{
id: 1,
title: 'take out trash',
done: false
},
{
id: 2,
title: 'wife to dinner',
done: false
},
{
id: 3,
title: 'make react app',
done: false
},
]
})
const toggleDone = (id) => {
console.log(id);
}
return (
<div className="App">
<Todos todos={state.todos} toggleDone={toggleDone}/>
</div> …Run Code Online (Sandbox Code Playgroud) 有人告诉我,每当我使用反应状态或更改它时,我都应该对其进行克隆或复制。
const cloneState = [...this.state]
cloneState.name = 'hardik'
Run Code Online (Sandbox Code Playgroud)
但我不知道为什么人们推荐它,为什么我不能直接改变状态?
为什么我不应该用它来做到这一点
this.setState({name: 'hardik'})
Run Code Online (Sandbox Code Playgroud) 我有一个 React 更改处理程序来监视一系列复选框。目标是拥有一个包含所有“已检查”条目的 State 数组。处理程序首先将当前状态复制到本地数组变量。然后它测试是否已检查,并将新条目推送到变量或将其从变量中拼接出来。最后,它将该变量设置回状态,为下一个周期做好准备。
问题是,当本地数组更改时,我的 State 数组会立即自动更改。怎么会发生这种事?!?!
这是我的处理程序代码:
handleEmpChange(parm1, parm2, event) {
const {name, value, checked} = event.target
console.log("name: ",name)
console.log("value: ",value)
console.log("checked: ",checked)
// Add the checked employee into the array (or remove it if unchecked)
let employeesArray = this.state.assignedTo
if (checked) {
console.log("employeesArray - before push: ",employeesArray)
console.log("this.state.assignedTo - before push: ",this.state.assignedTo)
console.log("this.state.originalAssignedTo - before push: ",this.state.originalAssignedTo)
employeesArray.push(value)
console.log("employeesArray - after push: ",employeesArray)
console.log("this.state.assignedTo - after push: ",this.state.assignedTo)
console.log("this.state.originalAssignedTo - after push: ",this.state.originalAssignedTo)
} else …Run Code Online (Sandbox Code Playgroud) 我正在关注 React 初学者教程,以制作待办事项应用程序为例。
在 App.js 中,有一个 handleChange 方法会更新状态是否选中复选框,并将其传递给 TodoItem 组件
class App extends React.Component {
constructor() {
super()
this.state = {
todos: todosData
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(id) {
console.log(id)
this.setState(prevState => {
const updatedTodos = prevState.todos.map(todo => {
if (todo.id === id) {
todo.completed = !todo.completed
}
return todo
})
return {
todos: updatedTodos
}
})
}
render() {
const todoItems = this.state.todos.map(item => <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>)
return (
<div className="todo-list">
{todoItems}
</div>
)
}
}
export …Run Code Online (Sandbox Code Playgroud) 我想知道我们setState()在 React 中仅用于更新状态的原因?
为什么我们不能做这个?
this.state.vote = this.state.vote + 1
Run Code Online (Sandbox Code Playgroud) 所以我这里有一些代码,它应该根据房产平方英尺和选择的包裹来计算价格。
当我像这样编写代码时,代码曾经与类组件一起使用......但我现在使用 react JS 和 Functional 组件。
我现在遇到的当前问题是让setBasePrice(1234);实际设置基本价格,以便它可以在函数中计算。
我也遇到了basePrice += basePrice * (percentage / 100);在功能组件中正常工作的问题。
我知道我现在完全错了,只是希望有人能指出我正确的方向,并可能告诉我如何清理我的代码。
更新
我添加了 useEffect 钩子,但总价出现错误。在 5500 平方英尺的价格应该是 272 美元,但出现了 112 美元。我的旧代码没有这样做,所以我不确定发生了什么。
类组件
this.state = {
propertySqft: "",
packageSelected: this.props.location.state,
totalPrice: null,
basePrice: null
};
}
checkPrice = () => {
debugger;
if(this.state.packageSelected === "Photography"){
this.state.basePrice = 159.998;
}else if(this.state.packageSelected === "Video"){
this.state.basePrice = 416.998;
}else if(this.state.packageSelected === "Drone Aerial Photos Only"){
this.state.basePrice = 199.998;
}else if(this.state.packageSelected === "Drone Aerial Video Only"){ …Run Code Online (Sandbox Code Playgroud) reactjs ×13
javascript ×8
react-hooks ×2
arrays ×1
ecmascript-6 ×1
math ×1
react-dom ×1
state ×1
typescript ×1
use-state ×1