推入状态数组的正确方法
Correct way to push into state array
我似乎在将数据推入状态数组时遇到了问题。
我正在尝试以这种方式实现它:
this.setState({ myArray: this.state.myArray.push('new value') })
但我认为这是不正确的方式并且会导致可变性问题?
数组推送returns长度
this.state.myArray.push('new value')
returns扩展数组的长度,而不是数组本身。Array.prototype.push().
我猜你希望返回值是数组。
不变性
这似乎是 React 的行为:
NEVER mutate this.state directly, as calling setState() afterwards may
replace the mutation you made. Treat this.state as if it were
immutable.React.Component.
我猜,你会这样做(不熟悉 React):
var joined = this.state.myArray.concat('new value');
this.setState({ myArray: joined })
您可以使用 .concat
方法用新数据创建数组的副本:
this.setState({ myArray: this.state.myArray.concat('new value') })
但要注意 .concat
方法在传递数组时的特殊行为 - [1, 2].concat(['foo', 3], 'bar')
将导致 [1, 2, 'foo', 3, 'bar']
.
你根本不应该操作状态。至少,不是直接的。如果你想更新你的阵列,你会想做这样的事情。
var newStateArray = this.state.myArray.slice();
newStateArray.push('new value');
this.setState(myArray: newStateArray);
直接在状态对象上工作是不可取的。您还可以查看 React 的不变性助手。
使用 es6 可以这样做:
this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array
React-Native
如果您还希望您的 UI(即您的 flatList)是最新的,请使用 PrevState:
在下面的示例中,如果用户单击按钮,它将向列表中添加一个新对象(在模型和 UI 中)
data: ['shopping','reading'] // declared in constructor
onPress={() => {this.setState((prevState, props) => {
return {data: [new obj].concat(prevState.data) };
})}}.
Never recommended to mutate the state directly.
在以后的 React 版本中推荐的方法是在修改状态时使用更新函数来防止竞争条件:
将字符串推到数组末尾
this.setState(prevState => ({
myArray: [...prevState.myArray, "new value"]
}))
将字符串推到数组的开头
this.setState(prevState => ({
myArray: ["new value", ...prevState.myArray]
}))
将对象推到数组末尾
this.setState(prevState => ({
myArray: [...prevState.myArray, {"name": "object"}]
}))
将对象推到数组的开头
this.setState(prevState => ({
myArray: [ {"name": "object"}, ...prevState.myArray]
}))
这段代码对我有用:
fetch('http://localhost:8080')
.then(response => response.json())
.then(json => {
this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})
通过以下方式我们可以检查和更新对象
this.setState(prevState => ({
Chart: this.state.Chart.length !== 0 ? [...prevState.Chart,data[data.length - 1]] : data
}));
这里不能像这样将对象推送到状态数组。你可以在普通数组中按你的方式推送。
这里要设置状态,
this.setState({
myArray: [...this.state.myArray, 'new value']
})
函数式组件和 React Hooks
const [array,setArray] = useState([]);
最后推送值:
setArray(oldArray => [...oldArray,newValue] );
开始推送值:
setArray(oldArray => [newValue,...oldArray] );
你违反了 React 原则,你应该克隆旧状态然后将其与新数据合并,你不应该直接操作你的状态,
你的代码应该是这样的
fetch('http://localhost:8080').then(response => response.json()).then(json ={this.setState({mystate[...this.state.mystate, json]}) })
使用react hooks,你可以按照下面的方式做
const [countryList, setCountries] = useState([]);
setCountries((countryList) => [
...countryList,
"India",
]);
我想这个回答有点晚了,但对于那些新手来说反应
你可以使用这个叫做 immer 的小包
setState([...prevState, {
label: newState.name,
value: newState.id
}]);
正在使用下拉菜单并想在那里实现这个场景,我找到了这个简单的多值下拉解决方案。
我似乎在将数据推入状态数组时遇到了问题。 我正在尝试以这种方式实现它:
this.setState({ myArray: this.state.myArray.push('new value') })
但我认为这是不正确的方式并且会导致可变性问题?
数组推送returns长度
this.state.myArray.push('new value')
returns扩展数组的长度,而不是数组本身。Array.prototype.push().
我猜你希望返回值是数组。
不变性
这似乎是 React 的行为:
NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.React.Component.
我猜,你会这样做(不熟悉 React):
var joined = this.state.myArray.concat('new value');
this.setState({ myArray: joined })
您可以使用 .concat
方法用新数据创建数组的副本:
this.setState({ myArray: this.state.myArray.concat('new value') })
但要注意 .concat
方法在传递数组时的特殊行为 - [1, 2].concat(['foo', 3], 'bar')
将导致 [1, 2, 'foo', 3, 'bar']
.
你根本不应该操作状态。至少,不是直接的。如果你想更新你的阵列,你会想做这样的事情。
var newStateArray = this.state.myArray.slice();
newStateArray.push('new value');
this.setState(myArray: newStateArray);
直接在状态对象上工作是不可取的。您还可以查看 React 的不变性助手。
使用 es6 可以这样做:
this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array
React-Native
如果您还希望您的 UI(即您的 flatList)是最新的,请使用 PrevState: 在下面的示例中,如果用户单击按钮,它将向列表中添加一个新对象(在模型和 UI 中)
data: ['shopping','reading'] // declared in constructor
onPress={() => {this.setState((prevState, props) => {
return {data: [new obj].concat(prevState.data) };
})}}.
Never recommended to mutate the state directly.
在以后的 React 版本中推荐的方法是在修改状态时使用更新函数来防止竞争条件:
将字符串推到数组末尾
this.setState(prevState => ({
myArray: [...prevState.myArray, "new value"]
}))
将字符串推到数组的开头
this.setState(prevState => ({
myArray: ["new value", ...prevState.myArray]
}))
将对象推到数组末尾
this.setState(prevState => ({
myArray: [...prevState.myArray, {"name": "object"}]
}))
将对象推到数组的开头
this.setState(prevState => ({
myArray: [ {"name": "object"}, ...prevState.myArray]
}))
这段代码对我有用:
fetch('http://localhost:8080')
.then(response => response.json())
.then(json => {
this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})
通过以下方式我们可以检查和更新对象
this.setState(prevState => ({
Chart: this.state.Chart.length !== 0 ? [...prevState.Chart,data[data.length - 1]] : data
}));
这里不能像这样将对象推送到状态数组。你可以在普通数组中按你的方式推送。 这里要设置状态,
this.setState({
myArray: [...this.state.myArray, 'new value']
})
函数式组件和 React Hooks
const [array,setArray] = useState([]);
最后推送值:
setArray(oldArray => [...oldArray,newValue] );
开始推送值:
setArray(oldArray => [newValue,...oldArray] );
你违反了 React 原则,你应该克隆旧状态然后将其与新数据合并,你不应该直接操作你的状态, 你的代码应该是这样的
fetch('http://localhost:8080').then(response => response.json()).then(json ={this.setState({mystate[...this.state.mystate, json]}) })
使用react hooks,你可以按照下面的方式做
const [countryList, setCountries] = useState([]);
setCountries((countryList) => [
...countryList,
"India",
]);
我想这个回答有点晚了,但对于那些新手来说反应
你可以使用这个叫做 immer 的小包
setState([...prevState, {
label: newState.name,
value: newState.id
}]);
正在使用下拉菜单并想在那里实现这个场景,我找到了这个简单的多值下拉解决方案。