我有这个小组件:
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 :(得分: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}/>
)
}
}