React Native:将状态从子状态更新为父状态,然后在第二个组件处传递更新的道具

时间:2019-06-22 16:35:13

标签: react-native

我正在尝试在第二次Recipe-Component更新状态时更改props的值。

我尝试使用计时器,警报。但是我也有问题。

应用js:

import React, { Component } from "react";
import Recipe from "./Recipe";
import {Text, View } from "react-native";


export default class App extends Component {
  constructor() {
    super();
    this.state = {
      name: "Pancaces",
      isYummy: true
    };
  }

  update = (s) => {
     this.setState({name : s.name, isYummy: s.isYummy });
  }

  render() {
    return (
      <View style={{alignItems: 'center'}}>
        <Recipe update={this.update} name={this.state.name} isYummy={this.state.isYummy}  delay={false}/>
        <Text>{this.state.name}</Text>
        <Recipe name={this.state.name} isYummy={this.state.isYummy} delay={true}/>

      </View>
    );
  }
}

Recipe.js

import React, * as react from "react";
import PropTypes from "prop-types";
import { Text, View } from "react-native";
import styles from "./styles.js";

export default class Recipe extends react.Component{

  static propTypes = {
    name: PropTypes.string.isRequired,
    isYummy: PropTypes.bool.isRequired
  };


  constructor(props){
      super(props)
      this.state = {
          update : this.update,
          name : this.props.name,
          isYummy: this.props.isYummy
      }
      if(this.props.update) this.props.update(({name:'Lentils', isYummy:false}))

  };



  render() {


    return (

      <View style={styles.container}>
        <Text  style={styles.text_container} >{this.state.name}</Text>
        {this.state.isYummy ? <Text>THIS RECIPE IS YUMMY</Text> : null}
      </View>

    );
  }
}

当前输出为:

煎饼 此食谱很美味 扁豆 薄煎饼 此食谱很美味

我希望输出

煎饼 此食谱很美味 扁豆 小扁豆

已解决

1 个答案:

答案 0 :(得分:1)

我相信这是因为您正在尝试显示状态而不是props中的值,并且由于更新后未再次调用构造函数,因此不会重新分配状态。这就是我要做的:

//Recipe.js

constructor (props) 
{
    super(props);

    if (this.props.update) 
        this.props.update(({name:'Lentils', isYummy:false}));
}

render()
{
    return (
        <View style={styles.container}>
            <Text  style={styles.text_container}> 
                {this.props.name}
            </Text>
        {this.props.isYummy &&
            <Text>
                THIS RECIPE IS YUMMY
            </Text>
        }
      </View>
    );
}