简体   繁体   English

ReactJs-以更高级的方式将prop传递给子组件

[英]ReactJs - passing props to a child component in a bit more advanced way

I'm making a card game and I have this db.json: 我正在做一个纸牌游戏,我有这个db.json:

{
  "characters": [   
    {    
      "name": "Character1",
      "punch":12,
      "kick":12,
      "special":15,
      "image":"character1"

    },
    {    
      "name": "Character2",
      "punch":13,
      "kick":11,
      "special":15,
      "image":"character2"  
    },         

    {   
      "name": "Character3",
      "punch":20,
      "kick":19,
      "special":10,
      "image":"character3"   
    },
    {   
      "name": "Character4",
      "punch":21,
      "kick":18,
      "special":2,
      "image":"character4"   
    }
  ]
}

So I have this parent component that is fetching the data to children components: 所以我有一个父组件正在将数据获取到子组件:

import React, { Component } from 'react'
import Player from './Player'

var data = require('./db.json');

class Stage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      characters: []
    }
  }

  componentDidMount() {
    this.setState({
      characters: data.characters
    })  
  }

  render() {
    return (

      <div className="stage">      
        <Player data={this.state.characters}/>
        <Player data={this.state.characters}/>
      </div>
    )
  }
}


export default Stage

Each <Player> component is receiving the same data. 每个<Player>组件都接收相同的数据。 I would like to distribute the data divided for each component. 我想分发为每个组件划分的数据。 For example, I have 4 characters and each component might receive 2 characters in a random way. 例如,我有4个字符,每个组件可能会随机接收2个字符。 For example to be more clear: 例如,要更清楚一点:

player 1: character1, character2 or character2, character4 or character3, character2 etc... 玩家1:character1,character2或character2,character4或character3,character2等...

the same thing for player 2 玩家2同样

each player might NOT have repeated characters. 每个玩家可能没有重复的角色。 How do I solve it? 我该如何解决?

Here is a <Player> component code 这是一个<Player>组件代码

import React from 'react'
import Card from './Card'   

const Player = ({data}) => { 
  return (
    <div className="player">   
      {data.map(character => (     
        <Card name={character.name}/>  
      ))}             
    </div>
  )
}    

export default Player

claudiobitar you will achieve this by below changes claudiobitar您将通过以下更改来实现

import React, {Component} from 'react'
import Player from './Player'

var data = require('./db.json');
let random = Math.floor(Math.random() * 4) + 1

class Stage extends Component {
    constructor(props) {
        super(props)
        this.state = {
            characters: [],
            set1: [],
            set2: []
        }
    }

    componentDidMount() {

        let {set1, set2} = this.state

        while (set1.length < 2) {
            !set1.includes(random) && this.setState({set1: [...set1, data.characters[random]]})
            random = Math.floor(Math.random() * 4) + 1
        }

        while (set2.length < 2) {
            !set2.includes(random) && this.setState({set2: [...set2, data.characters[random]]})
            random = Math.floor(Math.random() * 4) + 1
        }

        /*this.setState({
            characters: data.characters
        })*/
    }

    render() {

        let {set1, set2} = this.state

        return (

            <div className="stage">
                <Player data={this.state.set1}/>
                <Player data={this.state.set2}/>
            </div>
        )
    }
}


export default Stage

You can simply do it by adding a new state called player1 and player2, create a new array and pass it to the respective component. 您只需添加一个名为player1和player2的新状态,创建一个新数组并将其传递给相应的组件即可。

class Stage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      player1: [],
      player2: [],
    }
  }

  componentDidMount() {
    const shuffled = data.characters.sort(() => 0.5 - Math.random());
    const player1 = shuffled.slice(0, 2);
    const player2 = shuffled.slice(2,4);
    this.setState({
      player1,
      player2,
    })  
  }

  render() {
    return (
      <div className="stage">      
        <Player data={this.state.player1}/>
        <Player data={this.state.player2}/>
      </div>
    )
  }
}
    let a1= [], a2 = [], random = Math.floor(Math.random()*4) +1;

    while(a1.length < 2){
      !a1.includes(random) && a1.push(random)
      random = Math.floor(Math.random()*4) +1
    }

    while(a2.length < 2){
      !a1.includes(random) &&a2.push(random)
      random = Math.floor(Math.random()*4) +1
    }

console.log(a1, a2)

result ==> a1= [2,4] , a2 = [1,3] //randomly changing 结果==> a1 = [2,4],a2 = [1,3] //随机更改

try to divide you data before send to sub component. 尝试先将数据分割后再发送到子组件。 one way is, create 1 list with 2 sublist, that sublist will be send to sub component Player1 and Player2. 一种方法是,创建带有2个子列表的1个列表,该子列表将发送到子组件Player1和Player2。 try to distribute your character data in 2 sub lists in position 0 and 1 using a random number. 尝试使用随机数将字符数据分布在位置0和1的2个子列表中。

const lists = [[], []]
for (var i=0; i<(this.state.characters.lenght); i++) {
  const rand = Math.floor(Math.random() * 1);
  lists[rand].push(this.state.characters[i]) 
}

with that, you will be able to divide your list, but the next step is divide half for each side. 这样一来,您就可以对列表进行划分,但是下一步是将每一边都划分为一半。

i hope it useful, i will keep trying here. 我希望它有用,我会继续在这里尝试。

import React, { Component } from "react";
import Player from './Player'

var data = require("./db.json");

export default class Stage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      characters: []
    };
  }

  //function to get random list of objects
  foo(characters) {
    let randomNums = [];
    for (let i = 0; i < characters.length; i++) {
      randomNums.push(i);
    }
    let ind_1 = Math.floor(Math.random() * characters.length);
    randomNums.splice(ind_1, 1);
    let ind_2 = Math.floor(Math.random() * (characters.length - 1));
    ind_2 = randomNums[ind_2];
    console.log(ind_1);
    return [characters[ind_1], characters[ind_2]];
  }

  componentDidMount() {
    this.setState({
      characters: data.characters
    });
  }

  render() {
    return (
      <div className="stage">
        <Player data={this.foo(this.state.characters)} />
        <Player data={this.foo(this.state.characters)} />
      </div>
    );
  }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM