Reactjs React Native:.map循环内的动态状态分配出现错误

Reactjs React Native:.map循环内的动态状态分配出现错误,reactjs,react-native,Reactjs,React Native,我的代码目标: import React, {Component} from 'react'; import {View, Text, TouchableOpacity} from 'react-native'; export default class App extends Component { constructor(props) { super(props); this.state = { maths: {}, }; } prepar

我的代码目标:

import React, {Component} from 'react';
import {View, Text, TouchableOpacity} from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      maths: {},
    };
  }

  prepareMaths = function() {
    var count = 5;

    var updateMath = key => {
      var stateMaths = this.state.maths;
      stateMaths['position_' + key] = Math.random();

      this.setState({maths: stateMaths}, () => {
        console.log(this.state.maths);
      });
    };

    var stateMaths = this.state.maths;

    return [...Array(count)].map((options, key) => {
      stateMaths['position_' + key] = Math.random();
      this.setState({maths: stateMaths});

      return (
        <TouchableOpacity
          key={key}
          onPress={() => updateMath(key)}
          style={{
            height: 100,
            width: 200,
            marginRight: 20,
            marginBottom: 10,
            backgroundColor: 'green',
          }}>
          <Text>{this.state.maths['position_' + key]}</Text>
        </TouchableOpacity>
      );
    });
  };

  render() {
    return (
      <View>
        <View>{this.prepareMaths()}</View>
      </View>
    );
  }
}
  • 使用循环渲染某些视图元素
  • 在循环内部,设置状态
  • 单击元素后,更新该值
  • 这是我的代码:

    import React, {Component} from 'react';
    import {View, Text, TouchableOpacity} from 'react-native';
    
    export default class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          maths: {},
        };
      }
    
      prepareMaths = function() {
        var count = 5;
    
        var updateMath = key => {
          var stateMaths = this.state.maths;
          stateMaths['position_' + key] = Math.random();
    
          this.setState({maths: stateMaths}, () => {
            console.log(this.state.maths);
          });
        };
    
        var stateMaths = this.state.maths;
    
        return [...Array(count)].map((options, key) => {
          stateMaths['position_' + key] = Math.random();
          this.setState({maths: stateMaths});
    
          return (
            <TouchableOpacity
              key={key}
              onPress={() => updateMath(key)}
              style={{
                height: 100,
                width: 200,
                marginRight: 20,
                marginBottom: 10,
                backgroundColor: 'green',
              }}>
              <Text>{this.state.maths['position_' + key]}</Text>
            </TouchableOpacity>
          );
        });
      };
    
      render() {
        return (
          <View>
            <View>{this.prepareMaths()}</View>
          </View>
        );
      }
    }
    
    import React,{Component}来自'React';
    从“react native”导入{View,Text,TouchableOpacity};
    导出默认类应用程序扩展组件{
    建造师(道具){
    超级(道具);
    此.state={
    数学:{},
    };
    }
    prepareMaths=函数(){
    var计数=5;
    var updateMath=key=>{
    var stateMathy=this.state.mathy;
    stateMathm['position_'+key]=Math.random();
    this.setState({math:stateMath},()=>{
    console.log(this.state.mathematics);
    });
    };
    var stateMathy=this.state.mathy;
    返回[…数组(计数)].map((选项,键)=>{
    stateMathm['position_'+key]=Math.random();
    this.setState({math:stateMath});
    返回(
    更新路径(键)}
    风格={{
    身高:100,
    宽度:200,
    marginRight:20,
    marginBottom:10,
    背景颜色:“绿色”,
    }}>
    {this.state.mathematics['position.'+key]}
    );
    });
    };
    render(){
    返回(
    {this.prepareMaths()}
    );
    }
    }
    
    我在代码中遇到此错误:

    import React, {Component} from 'react';
    import {View, Text, TouchableOpacity} from 'react-native';
    
    export default class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          maths: {},
        };
      }
    
      prepareMaths = function() {
        var count = 5;
    
        var updateMath = key => {
          var stateMaths = this.state.maths;
          stateMaths['position_' + key] = Math.random();
    
          this.setState({maths: stateMaths}, () => {
            console.log(this.state.maths);
          });
        };
    
        var stateMaths = this.state.maths;
    
        return [...Array(count)].map((options, key) => {
          stateMaths['position_' + key] = Math.random();
          this.setState({maths: stateMaths});
    
          return (
            <TouchableOpacity
              key={key}
              onPress={() => updateMath(key)}
              style={{
                height: 100,
                width: 200,
                marginRight: 20,
                marginBottom: 10,
                backgroundColor: 'green',
              }}>
              <Text>{this.state.maths['position_' + key]}</Text>
            </TouchableOpacity>
          );
        });
      };
    
      render() {
        return (
          <View>
            <View>{this.prepareMaths()}</View>
          </View>
        );
      }
    }
    

    我很困惑。因为如果我删除循环中的
    setState…
    code,它自然会显示随机数学。但是怎么做呢?因为我在渲染时使用了
    this.state.mathematics['position.'+key]
    。我真的不知道这些数据是如何产生的

    请帮忙。 提前感谢。

    问题
  • 状态突变

    var stateMaths = this.state.maths; // <-- state
    stateMaths['position_' + key] = Math.random(); // <-- mutation!!
    
  • 解决方案
  • prepareMath
    updateMath
    分解为独立的实用程序函数
  • 数学
    状态转换为数组
  • 使用
    componentDidMount
    初始化状态
  • 使用
    componentdiddupdate
    记录更新状态
  • 将JSX从状态映射的
    prepareMaths
    移动到
    render
    函数
  • 更新组件

    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          maths: [],
        };
      }
    
      componentDidMount() {
        this.prepareMaths();
      }
    
      componentDidUpdate() {
        console.log(this.state.maths);
      }
    
      updateMath = (key) => {
        this.setState((prevState) => ({
          maths: prevState.maths.map((el, i) => (i === key ? Math.random() : el)),
        }));
      };
    
      prepareMaths = function () {
        const count = 5;
    
        this.setState({ maths: [...Array(count)].map(Math.random) });
      };
    
      render() {
        const { maths } = this.state;
        return (
          <View>
            <View>
              {maths.map((value, key) => (
                <TouchableOpacity
                  key={key}
                  onPress={() => this.updateMath(key)}
                  style={{
                    height: 100,
                    width: 200,
                    marginRight: 20,
                    marginBottom: 10,
                    backgroundColor: 'green',
                  }}>
                  <Text>{value}</Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>
        );
      }
    }
    
    类应用程序扩展了React.Component{
    建造师(道具){
    超级(道具);
    此.state={
    数学:[],
    };
    }
    componentDidMount(){
    这是prepareMaths();
    }
    componentDidUpdate(){
    console.log(this.state.mathematics);
    }
    updateMath=(键)=>{
    this.setState((prevState)=>({
    数学:prevState.Math.map((el,i)=>(i==key?Math.random():el)),
    }));
    };
    prepareMaths=函数(){
    常数计数=5;
    this.setState({Math:[…数组(计数)].map(Math.random)});
    };
    render(){
    const{math}=this.state;
    返回(
    {math.map((值,键)=>(
    this.updateMath(key)}
    风格={{
    身高:100,
    宽度:200,
    marginRight:20,
    marginBottom:10,
    背景颜色:“绿色”,
    }}>
    {value}
    ))}
    );
    }
    }
    

    您不能从渲染函数更新状态,因为这将触发另一个渲染周期。@DrewReese,谢谢。但是我该怎么做呢?请提供解决方案。
    this.setState({math:stateMath})的目的是什么在映射循环中?这将首次将数据保存到状态,因为该数据在构造函数中为空。是的,对其进行了更深入的研究,并怀疑这是试图提供“初始状态”来呈现某些内容。