简体   繁体   English

如何返回 React 容器的数值而不是 object?

[英]How can I return the numeric value of a React container instead of an object?

I'm trying to learn React and am working on a simple web app to implement what I've learned online so far.我正在尝试学习 React,并且正在开发一个简单的 web 应用程序来实现我迄今为止在网上学到的东西。

I have a container called CardDatabase.js and all it returns is a single value.我有一个名为CardDatabase.js的容器,它返回的只是一个值。 This value is called reduceArray and it's an array that has had the reduce() method called on it.这个值称为reduceArray ,它是一个调用了reduce()方法的数组。 When I render <CardDatabase.js /> the value appears in the browser and in the console as intended (in the screenshot, it's 86).当我渲染<CardDatabase.js />时,值会按预期出现在浏览器和控制台中(在屏幕截图中,它是 86)。 However, when I try to assign the value of <CardDatabase /> to variable w inside of the calculate method in App.js , an object is returned instead of a numeric value (check the console in the screenshot).但是,当我尝试将<CardDatabase />的值分配给App.js中的calculate方法内的变量w时,会返回 object 而不是数值(检查屏幕截图中的控制台)。

在此处输入图像描述

How can I assign the numeric value of <CardDatabase /> to a variable so that I can use it to calculate some simple math?如何将<CardDatabase />的数值分配给变量,以便我可以使用它来计算一些简单的数学?

I also tried using props and this.state but according to the console error I got and the React docs, we cannot modify the value of props?我也尝试使用 props 和this.state但是根据我得到的控制台错误和 React 文档,我们不能修改 props 的值? So when I tried something like:所以当我尝试类似的事情时:

const array = (rarityOfArray) => {
        filteredArray = rarityOfArray.filter(item => item.key <= level)

        for(let x = 0; x < filteredArray.length; x++) {
            pushedArray.push(filteredArray[x].cardsRequiredToUpgrade)
            console.log(pushedArray);
        }

        props.array = pushedArray.reduce((a, b) => a + b, 0);
        console.log("Reduced - " + reducedArray);

        return props.array
    }

I got this error message: TypeError: Cannot assign to read only property 'array' of object '#<Object>'我收到此错误消息: TypeError: Cannot assign to read only property 'array' of object '#<Object>'

Any help or direction would be greatly appreciated.任何帮助或方向将不胜感激。


App.js应用程序.js

import React, {Component} from 'react';

// CSS
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';

// Components 
import CardRarityDropdown from './components/CardRarityDropdown';
import CardLevelDropdown from './components/CardLevelDropdown';
import CardAmountInput from './components/CardAmountInput';
import CardCalculationsButton from './components/CardCalculationsButton';

//Containers
import CardDatabase from './containers/cardDatabase/CardDatabase';

class App extends Component {

  constructor() {
    super();
    this.state = {
      cardRarity: "",
      cardLevel: "",
      amountOfCards: "",
    }
    this.setCardValues = this.setCardValues.bind(this);
  }

  setCardValues = (event) => {
    const {name, value} = event.target

    this.setState({
          [name]: value
    })
  }

  calculate = () => {
    let v = this.state.cardRarity;
    console.log("v: " + v)

    let w = <CardDatabase />
    console.log("w: " + w)

    let x = v - w;
    console.log("x: " + x)

    let y = this.state.amountOfCards;
    console.log("y: " + y)

    let z = x - y;
    console.log("z: " + z)

    return z
  }

  render () {
    return (

        <div>
          <h1 id="superCellText">Clash Royale Card Calculator</h1>

          <CardRarityDropdown
            setCardValues={this.setCardValues}
            cardRarity={this.state.cardRarity} />

          <CardLevelDropdown
            setCardValues={this.setCardValues}
            cardRarity={this.state.cardRarity}
            cardLevel={this.state.cardLevel} />

          <CardDatabase
            cardRarity={this.state.cardRarity}
            cardLevel={this.state.cardLevel} />

          <CardAmountInput
            setCardValues={this.setCardValues}
            cardRarity={this.state.cardRarity}
            amountOfCards={this.state.amountOfCards} />

          <CardCalculationsButton
            calculate={this.calculate}
            cardRarity={this.state.cardRarity} />
        </div> 
    );
  }
}
export default App;


CardDatabase.js CardDatabase.js

import common from './Common';
import rare from './Rare';
import epic from './Epic';
import legendary from './Legendary';


const CardDatabase = (props) => {

    const card = props.cardRarity;
    const level = props.cardLevel;
    let filteredArray = [];
    let pushedArray = [];
    let reducedArray = [];

    const array = (rarityOfArray) => {
        filteredArray = rarityOfArray.filter(item => item.key <= level)

        for(let x = 0; x < filteredArray.length; x++) {
            pushedArray.push(filteredArray[x].cardsRequiredToUpgrade)
            console.log(pushedArray);
        }

        reducedArray = pushedArray.reduce((a, b) => a + b, 0);
        console.log("Reduced - " + reducedArray);

        return reducedArray
    }

    if(card === "9586") {return array(common)}

    if(card === "2586") {return array(rare)}

    if(card === "386") {return array(epic)}

    if(card === "36") {return array(legendary)}

    if(card === "")  {return null}
}
export default CardDatabase;

Folks on Reddit and Discord were giving me the same feedback, I shouldn't be using a component if said component isn't returning anything UI-related. Reddit 和 Discord 上的人们给了我相同的反馈,如果该组件没有返回任何与 UI 相关的内容,我不应该使用该组件。 Therefore, CardDatabase.js shouldn't be a component but a simple function instead.因此, CardDatabase.js不应该是一个组件,而是一个简单的 function。

I changed its name to cardDatabase.js so that React no longer considers it a component and instead of it receiving props, the function now has standard parameters.我将其名称更改为cardDatabase.js ,以便 React 不再将其视为组件,而不是接收道具,function 现在具有标准参数。

Updated cardDatabase.js更新了 cardDatabase.js

import common from './Common';
import rare from './Rare';
import epic from './Epic';
import legendary from './Legendary';


const cardDatabase = (cardRarity, cardLevel) => {

    let filteredArray = [];
    let pushedArray = [];
    let reducedArray = [];

    const array = (rarityOfArray) => {
        filteredArray = rarityOfArray.filter(item => item.key <= cardLevel)

        for(let x = 0; x < filteredArray.length; x++) {
            pushedArray.push(filteredArray[x].cardsRequiredToUpgrade)
            console.log(pushedArray);
        }

        reducedArray = pushedArray.reduce((a, b) => a + b, 0);
        console.log("Reduced - " + reducedArray);

        return reducedArray
    }

    if(cardRarity === "9586") {return array(common)}

    if(cardRarity === "2586") {return array(rare)}

    if(cardRarity === "386") {return array(epic)}

    if(cardRarity === "36") {return array(legendary)}

    if(cardRarity === "")  {return null}
}
export default cardDatabase;


In App.js I removed the <CardDatabase /> component and inside of my calculate method, simply assigned the value of variable w to my cardDatabase function with this.state.cardRarity and this.state.cardLevel as the arguments. In App.js I removed the <CardDatabase /> component and inside of my calculate method, simply assigned the value of variable w to my cardDatabase function with this.state.cardRarity and this.state.cardLevel as the arguments.

Updated App.js更新了 App.js

import React, {Component} from 'react';

// CSS
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';

// Components 
import CardRarityDropdown from './components/CardRarityDropdown';
import CardLevelDropdown from './components/CardLevelDropdown';
import CardAmountInput from './components/CardAmountInput';
import CardCalculationsButton from './components/CardCalculationsButton';

//Containers
import cardDatabase from './containers/cardDatabase/cardDatabase.js';

class App extends Component {

  constructor() {
    super();
    this.state = {
      cardRarity: "",
      cardLevel: "",
      amountOfCards: "",
    }
    this.setCardValues = this.setCardValues.bind(this);
  }

  setCardValues = (event) => {
    const {name, value} = event.target

    this.setState({
          [name]: value
    })
  }

  calculate = () => {
    let rarity = this.state.cardRarity;
    let level = this.state.cardLevel;
    console.log("v: " + rarity)

    let w = cardDatabase(rarity, level);
    console.log("w: " + w)

    let x = rarity - w;
    console.log("x: " + x)

    let y = this.state.amountOfCards;
    console.log("y: " + y)

    let z = x - y;
    console.log("z: " + z)

    return z
  }

  render () {
    return (

        <div>
          <h1 id="superCellText">Clash Royale Card Calculator</h1>

          <CardRarityDropdown
            setCardValues={this.setCardValues}
            cardRarity={this.state.cardRarity} />

          <CardLevelDropdown
            setCardValues={this.setCardValues}
            cardRarity={this.state.cardRarity}
            cardLevel={this.state.cardLevel} />

          <CardAmountInput
            setCardValues={this.setCardValues}
            cardRarity={this.state.cardRarity}
            amountOfCards={this.state.amountOfCards} />

          <CardCalculationsButton
            calculate={this.calculate}
            cardRarity={this.state.cardRarity} />
        </div> 
    );
  }
}
export default App;


Now w is returning a numerical value instead of an object and my app is finally functioning properly.现在w返回一个数值而不是 object 并且我的应用程序终于可以正常运行了。

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何返回对象而不是数组? - How can I return an object instead of an array? 如果参数是数字,我怎样才能让雪花中的 javascript 函数返回一个值,如果参数不是数字,我如何返回另一个值? - How can I get a javascript function in snowflake to return one value if the argument is numeric or another value if the argument is not numeric? 如何获取javascript对象(如窗口而不是字符串[object])的数值或字符串值 - How do I get a numeric or string value for a javascript object such as window instead of the string [object] 如何将组件对象传递给 React.js 中的容器? - How can I pass component object to container in React.js? 如何在Meteor和React中将对象从容器传递到类? - How can I pass an object from container to class in Meteor and React? 如何在对象中使用方法返回具有动态值的对象? - How can I have a method in an Object return an object with a dynamic value? 如何在 javaScript 中获得点击而不是 [object MouseEvent] 的价值 - How can i get value on click instead of [object MouseEvent] in javaScript 如何将 JSX 反应对象返回到网页? - How can I return a JSX react object to the webpage? 如何在 React 中过滤双精度数组并返回 object? - How can I filter a double array and return an object in React? 如何在MeteorJS / React中将对象存储在变量中以稍后返回? - How can I store an object in MeteorJS/React in a variable to return later?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM