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

时间:2019-03-05 05:43:02

标签: javascript reactjs

我正在玩纸牌游戏,我有这个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"   
    }
  ]
}

因此,我有一个父组件正在将数据获取到子组件:

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

每个<Player>组件都接收相同的数据。我想分发为每个组件划分的数据。例如,我有4个字符,每个组件可能会随机接收2个字符。例如,要更加清楚:

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

玩家2都一样

每个玩家可能没有重复的字符。 我该如何解决?

这是<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

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您只需添加一个名为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>
    )
  }
}

答案 2 :(得分:0)

    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)

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

答案 3 :(得分:0)

在发送到子组件之前尝试对数据进行划分。 一种方法是,创建带有2个子列表的1个列表,该子列表将发送到子组件Player1和Player2。 尝试使用随机数将字符数据分布在位置0和1的2个子列表中。

public class classC{
 private SharableObject object1;
 private SharableObject object2;

 public classC(){
  //initiliaze objects
  object1 = new SharableObject();
  object2 = new SharableObject();
 }

 private classA aClass = new classA(object1, object2);
 private classB bClass = new classB(object1, object2);

//since they refer same objects you can get data from classB when you change data from classA

这样,您就可以对列表进行划分,但是下一步是将每一面都划分为一半。

我希望它有用,我会继续在这里尝试。

答案 4 :(得分:0)

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>
    );
  }
}