React - Redux获取数据onclick和rerender

时间:2017-08-27 17:08:08

标签: reactjs redux react-redux

美好的一天!我想做动态下拉菜单,从服务器获取数据。因此,如果单击菜单项,我想从服务器获取数据并在列表中呈现结果。像这样:

import React, {Component} from 'react'
import {connect} from 'react-redux'
import {fetchData} from 'actions'

class MenuItem extends Component {
constructor(props) {
    super(props);
    this.state = {
        isOpened: false,
    }
}

toggleOpen() {
    this.props.fetchData(); // Here is fetching data using redux-thunk
    this.setState({isOpened: !this.state.isOpened});
}

render() {
    const {data} = this.props;

    return (
            <a href="#" className="left-menu__link"
               {...( this.state.isOpened && {
                   className: "left-menu__link is-opened"
               } )}
               onClick={(e) => {
                   e.preventDefault();
                   this.toggleOpen.bind(this)();
               }}>

            <ul className="left-menu__sub-level">
                {!R.isEmpty(data) && data.map((item) =>
                    <li item={item} key={item.id}/>)}
            </ul>
    )
}

const mapStateToProps = state => ({
    data: getData(state), // get data from state
});

const mapDispatchToProps = {
    fetchData
};

export default connect(mapStateToProps, mapDispatchToProps)(MenuItem)

那么你能告诉我哪种方法最好吗?

1 个答案:

答案 0 :(得分:0)

这里我更改了一些代码。我希望它会有所帮助

import React, {Component} from 'react'
import {connect} from 'react-redux'
import {fetchData} from 'actions'

class MenuItem extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isOpened: false
        }

        this.handleClick = this.handleClick.bind(this)
    }

    handleClick(e) {
        e.preventDefault()
        this.setState({isOpened: !this.state.isOpened})
        this.props.fetchData().then((response) => {
            ....
            ....
        })
    }

    render() {
        const {data} = this.props;
        const className = !this.state.isOpened ? 'left-menu__link' : 'left-menu__link is-opened'

        return (
                <a href="#" className={className}
                   onClick={this.handleClick}>

                <ul className="left-menu__sub-level">
                    {!R.isEmpty(data) && data.map((item) =>
                        <li item={item} key={item.id}/>)}
                </ul>
        )
    }
}
const mapStateToProps = state => ({
    data: getData(state), // get data from state
});

const mapDispatchToProps = {
    fetchData
};

export default connect(mapStateToProps, mapDispatchToProps)(MenuItem)