我想知道我是否可以在同一个函数中多次使用 setState 钩子。例如,像这样
import React, { useEffect, useState } from 'react';
function(props) {
const [color, setColor] = useState(0)
const [size, setSize]= useState(0)
const [weight, setWeight] = useState(0)
const onClickRandomButton = () => {
setColor(Math.random() * 10)
setSize(Math.random() * 10)
setWeight(Math.random() * 10)
}
return <div>
<button onClick = {onClickRandomButton}>random</button>
</div>
}
Run Code Online (Sandbox Code Playgroud)
我已经测试过了,但它没有按预期工作。使用钩子一次设置多个值,我该怎么办?谢谢
我有一个凸起按钮列表,我希望所选按钮的背景颜色在其 onPressed() 中更改
我尝试更改 setState 中的颜色,但它没有做任何事情。
这是生成按钮列表的函数
List<Widget> _makeZoneList(List<Zone> zones) {
List<Widget>Buttons = new List();
for (int i = 0; i < zones.length; i++) {
Buttons.add(RaisedButton(
color: zones[i].isSelected ? AppColors.primaryColor : AppColors.white,
onPressed: () {
setState(() {
if (zones[i].isSelected){
zones[i].isSelected = false;
}
else{
zones[i].isSelected = true;
}
print(zones[i].isSelected.toString());
});
},
child: Text(zones.elementAt(i).text)
));
}
return Buttons;
}
Run Code Online (Sandbox Code Playgroud)
这是我调用函数的地方
Widget _zoneBody() {
return Padding(
padding: EdgeInsets.all(32),
child: StreamBuilder<List<Zone>>(
stream: GetterBloc.zonesStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return …Run Code Online (Sandbox Code Playgroud) 我正在 React 中使用深度嵌套的状态对象。我的代码库要求我们尝试坚持使用函数组件,因此每次我想更新嵌套对象内的键/值对时,我都必须使用钩子来设置状态。不过,我似乎无法了解更深层次的嵌套项目。我有一个带有 onChange 处理程序的下拉菜单。. .in 的 onChange 处理程序是一个内联函数,可以直接设置正在更改的任何键/值对的值。
但是,我在每个内联函数中的展开运算符之后使用的语法是错误的。
作为一种解决方法,我已经将内联函数分解为它自己的函数,每次状态更改时都会重写整个状态对象,但这是非常耗时和丑陋的。我宁愿像下面这样内联:
const [stateObject, setStateObject] = useState({
top_level_prop: [
{
nestedProp1: "nestVal1",
nestedProp2: "nestVal2"
nestedProp3: "nestVal3",
nestedProp4: [
{
deepNestProp1: "deepNestedVal1",
deepNestProp2: "deepNestedVal2"
}
]
}
]
});
<h3>Top Level Prop</h3>
<span>NestedProp1:</span>
<select
id="nested-prop1-selector"
value={stateObject.top_level_prop[0].nestedProp1}
onChange={e => setStateObject({...stateObject,
top_level_prop[0].nestedProp1: e.target.value})}
>
<option value="nestVal1">nestVal1</option>
<option value="nestVal2">nestVal2</option>
<option value="nestVal3">nestVal3</option>
</select>
<h3>Nested Prop 4</h3>
<span>Deep Nest Prop 1:</span>
<select
id="deep-nested-prop-1-selector"
value={stateObject.top_level_prop[0].nestprop4[0].deepNestProp1}
onChange={e => setStateObject({...stateObject,
top_level_prop[0].nestedProp4[0].deepNestProp1: e.target.value})}
>
<option value="deepNestVal1">deepNestVal1</option>
<option value="deepNestVal2">deepNestVal2</option>
<option value="deepNestVal3">deepNestVal3</option>
</select> …Run Code Online (Sandbox Code Playgroud) 我有两个反应组件,我想调用 setState 在一个组件中设置状态,但在另一个组件中调用。我怎么做?
我是iOS开发人员,目前正在开发一个实验性的React Native应用程序.我有以下代码,在屏幕上显示一个按钮和示例文本.
import React from 'react';
import { StyleSheet, Text, View , Button } from 'react-native';
export default class App extends React.Component {
constructor() {
super();
this.state = {sampleText: 'Initial Text'};
}
changeTextValue = () => {
this.setState({sampleText: 'Changed Text'});
}
_onPressButton() {
<Text onPress = {this.changeTextValue}>
{this.state.sampleText}
</Text>
}
render() {
return (
<View style={styles.container}>
<Text onPress = {this.changeTextValue}>
{this.state.sampleText}
</Text>
<View style={styles.buttonContainer}>
<Button
onPress={this._onPressButton}
title="Change Text!"
color="#00ced1"
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: …Run Code Online (Sandbox Code Playgroud) 当我们想要重建StatefulWidget时,我们会调用setState()但是如果我们输入的代码在该函数内部或在其外部,那真的很重要吗?
这是:
class _ShoppingListState extends State<ShoppingList> {
Set<Product> _shoppingCart = new Set<Product>();
void _handleCartChanged(Product product, bool inCart) {
setState(() {
if (inCart)
_shoppingCart.add(product);
else
_shoppingCart.remove(product);
});
}
}
Run Code Online (Sandbox Code Playgroud)
与此相同:
class _ShoppingListState extends State<ShoppingList> {
Set<Product> _shoppingCart = new Set<Product>();
void _handleCartChanged(Product product, bool inCart) {
if (inCart)
_shoppingCart.add(product);
else
_shoppingCart.remove(product);
});
setState((){});
}
}
Run Code Online (Sandbox Code Playgroud) 我尝试在 {AbsorbPointer} (特别是 {GestureDetector} onPanEnd)调用的 'fling' 函数的 SetState() 内使用 'showGeneralDialog' 编写动画对话框脚本。我附加了简单的代码,我尝试用未来的异步等待等来完成它,但可能我不明白。
\n“child: EasyDialog”在我的代码中定义为 void 函数。\n这是我的调试控制台和附加的代码
\n如果有人能指导我如何在 setState 期间完成动画(pageBuilder),我会很高兴。
\n[38;5;248m\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90 Exception caught by widgets library \xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90[39;49m\n[38;5;244mThe following assertion was thrown building Builder(dirty, dependencies: [_LocalizationsScope-[GlobalKey#3e9b6]]):[39;49m\nsetState() or markNeedsBuild() called during build.\n\n[38;5;244mThis Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its …Run Code Online (Sandbox Code Playgroud) 是否可以在this.setState的回调中调用this.setState?
我正在制作一个Roguelike Dungeon并且有一个设置,在this.setState的回调中使用了一个辅助函数,它再次调用this.setState.我的游戏冻结了.
所以我在React组件中有一个对象,它有一个生成随机2D数组映射的方法:
this.Dungeon.Generate();
Run Code Online (Sandbox Code Playgroud)
当游戏开始时,我们在componentDidMount()中调用组件中的以下函数:
componentDidMount: function() {
this.Dungeon.Generate();
this.setState({
board: this.Dungeon.map
}, function() {
this.generateGamePlay();
});
},
Run Code Online (Sandbox Code Playgroud)
this.generateGamePlay()看起来像这样,基本上生成并将玩家,老板和物品随机放在棋盘上:
generateGamePlay: function() {
var board = this.state.board.slice();
var startPosition = this.randomPosition();
board[startPosition[0]][startPosition[1]] = this.state.player;
var bossPosition = this.randomPosition();
board[bossPosition[0]][bossPosition[1]] = this.state.boss[this.state.dungeonLevel];
this.generateWeapons(this.state.dungeonLevel,board);
this.generateFood(this.state.dungeonLevel, board);
this.generateEnemies(this.state.dungeonLevel, board);
this.setState({
board: board
});
},
Run Code Online (Sandbox Code Playgroud)
但是当玩家死亡时,我们再次呼叫以重置游戏:
this.Dungeon.Generate();
//generate a new dungeon map, available in this.Dungeon.map
this.setState({
board: this.Dungeon.map, currentMessage: "Game restarted", player: player, weapon: weapon, dungeonLevel: 0
}, function(){
this.generateGamePlay();
})
Run Code Online (Sandbox Code Playgroud)
但是当我的游戏冻结时.所以我第一次调用this.generateGamePlay()(调用this.setState)它可以工作,但第二次冻结.有人可以帮帮我吗?
我在这篇官方文章中读过以下这些文章:
this.props并且this.state可以异步更新,您不应该依赖它们的值来计算下一个状态.
任何人都可以通过举例说明以下代码试图实现的内容.
this.setState((prevState, props) => ({
couter: prevState.counter + props.increment
}));
Run Code Online (Sandbox Code Playgroud)
当我用酶测试类组件时,我可以wrapper.setState({})设置状态。当我用useState()钩子测试功能组件时,现在该怎么做?
例如,在我的组件中,我有:
const [mode, setMode] = useState("my value");
Run Code Online (Sandbox Code Playgroud)
我想改变mode测试范围
setstate ×10
reactjs ×7
javascript ×5
flutter ×3
react-hooks ×3
dart ×2
state ×2
callback ×1
components ×1
enzyme ×1
ios ×1
overlay ×1
react-native ×1