如何使React Component在每个状态变化时都调用一个函数?

时间:2018-07-29 00:06:31

标签: javascript reactjs npm state

使用此组件,像往常一样,每次更新都会调用getDisplay(因此,在单击时将其隐藏):

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = { show: true }
    }
    getDisplay = () => this.state.show ? 'block' : 'none';
    getStyle = () => { { display: this.getDisplay() } }
    render = () => <div style={{ display: this.getDisplay() }} onClick={() => { console.log('clicked'); this.setState({ show: false }) }}>
        <p>TEST</p>
    </div >
}

问题在这里: 当我将render元素移动到一个数组,然后在render函数中返回该数组时,它可以工作,但是getDisplay函数仅在初始化数组时才被调用,并且不会每次都被调用,因此在这种情况下,单击不会隐藏

class Example extends React.Component {
    array = []
    constructor(props) {
        super(props);
        this.state = { show: true }
        //getDisplay is called here instead of getting called on every render/state change.
        this.array.push(
            <div style={{ display: this.getDisplay() }} onClick={() => { console.log('clicked'); this.setState({ show: false }) }}>
                <p>TEST</p>
            </div >
        )
    }
    getDisplay = () => this.state.show ? 'block' : 'none';
    getStyle = () => { { display: this.getDisplay() } }
    render = () => this.array
}

这是我正在处理的应用程序的一个最小示例,我需要将保存html元素的数组分开,并使render函数返回它。如何使第二个代码示例中的每个状态更改都调用getDisplay? 我希望我能正确解释,_,

1 个答案:

答案 0 :(得分:1)

问题是class App extends React.Component { constructor () { super() this.state = { view: 'feed', posts: '' //data I want to render } this.changeView = this.changeView.bind(this) } componentDidMount () { this.getAllPosts() //getting the data } getAllPosts () { axios.get('/api/blogs') .then((response) => { console.log(response) this.setState({ posts: response }) }) .catch((error) => { console.log(error) }) } changeView(option) { this.setState({ view: option }) } renderView () { const {view} = this.state if (view === 'feed') { return <Feed blogs={this.state.posts} handleClick={() => this.changeView('anypostview')}/> //passing data as props in Feed blogs } else { return <Post /> } } render() { return ( <div> <div className="nav"> <span className="logo" onClick={() => this.changeView('feed')}> BLOGMODO </span> <span className={this.state.view === 'feed' ? 'nav-selected' : 'nav-unselected'} onClick={() => this.changeView('feed')}> See all Posts </span> <span className="nav-unselected"> Write a Post </span> <span className="nav-unselected"> Admin </span> </div> <div className="main"> {this.renderView()} </div> </div> ); } } 是静态的。在构建时,您正在构建阵列,而永远不会重新访问它。与其在构造函​​数中构建JSX,不如将数据填充到数组中,然后在渲染器上映射它。

this.array

请注意,b / c render: () => this.array.map(item => ( /* JSX for each item goes here. */ )) 尚未处于状态,向其中添加新项目不会自动更新它。如果您想要这种行为,请确保您a)将其存储为状态(例如this.array),并且b)不要对其进行突变(即不要使用this.state = { show: true, array: [] },而使用.push