2017-08-29 76 views
0

我有这个小部件:调用其他组件的方法

import React from 'react'; 

const Footer = (props) => { 
    return (
    <footer className="top"> 
     <p>{props.items} items in your menu</p> 
    </footer> 
) 
} 

const updateItems = (n) => { 
    this.props.items = this.props.items + n; 
}; 

Footer.propTypes = { 
    items: React.PropTypes.string.isRequired 
}; 

export default Footer; 

而且从主要成分:

// All irrelevant imports 
import Footer from './Footer'; 

class App extends React.Component { 
    // All the irrelevant vars and methods 

    removeFish = (key) => { 
     const fishes = {...this.state.fishes}; 
     fishes[key] = null; 
     this.setState({ fishes }); 
     Footer.updateItems(-1); // <-- This is not updating the items count in the footer component 
    }; 
} 

我Footer.updateItems似乎并没有更新的价值,甚至控制台火没有错误,应用程序符合,

这将是正确的方法?

+0

'updateItems'应该是Footer组件的一个方法,并更新Footer状态的值,而不是道具。 – Andrew

回答

2

首先 updateItems不是页脚组件的功能

其次,你不应该直接更改的道具,你需要改变你的构造和处理在App组件的更新,让Footer是纯,因为它是一个无状态组件

import React from 'react'; 

const Footer = (props) => { 
    return (
    <footer className="top"> 
     <p>{props.items} items in your menu</p> 
    </footer> 
) 
} 

Footer.propTypes = { 
    items: React.PropTypes.string.isRequired 
}; 

export default Footer; 

应用

// All irrelevant imports 
import Footer from './Footer'; 

class App extends React.Component { 
    // All the irrelevant vars and methods 

    removeFish = (key) => { 
     const fishes = {...this.state.fishes}; 
     fishes[key] = null; 
     this.setState({ fishes }); 

     this.updateItems(-1); 
    }; 
    updateItems = (n) => { 
     this.setState((prevState) => ({items: prevState.items + n})) 
    }; 
    render(){ 
     return (
       <Footer items={this.state.items}/> 
     ) 
    } 
} 
+0

对不起,以前测试,事情是,我得到这个错误'warning.js:35警告:失败的道具类型:所需的道具项目未在页脚中指定。在页脚(在App.js:129)在应用程序(由匹配创建)..'在控制台..任何想法为什么? –

+0

您需要将项目初始化为App组件中的字符串 –