Выполнять действие только для выбранных дочерних элементов в родительском Компоненте - PullRequest
0 голосов
/ 03 августа 2020

В моем приложении реакции у меня есть компонент родительского списка Тесты :

 export class Items extends Component {

    static propTypes = {
        tests: PropTypes.array.isRequired,
        getItems: PropTypes.func.isRequired
    };

    componentDidMount() {
        this.props.getItems();
    }

    render() {
        return (
            <Fragment>
                <Filters />
                {this.props.items.map((item) => (
                    <Item key={item.id} item={item} />
                ))}
            </Fragment>
        );
    }
}

const mapStateToProps = (state) => ({
    items: state.items.items
});

export default connect(mapStateToProps, { getItems })(Items);

getItems и getItem действия:

export const getItems = () => dispatch => {
    axios.get('/api/items/')
        .then(res => {
            dispatch({
                type: GET_ITEMS,
                payload: res.data
            });
        })
        .catch(err => console.log(err))
    
export const getItem = (id) => dispatch => {
        axios.get(`/api/items/${id}`)
            .then(res => {
                dispatch({
                    type: GET_ITEM,
                    payload: id
                });
            })
            .catch(err => console.log(err))

и дочерние элементы Предмет Компонент:

export class Item extends Component {

    render() {
        return (
            <div key={this.props.item.id} className="main"> 
               <p>{this.props.item.title}</p>
            </div>
        )
    }
}

const mapStateToProps = (state) => ({
    items: state.items.items
});

export default connect(mapStateToProps, { getItem })(Item);

когда вы нажимаете Компонент предмета для его получения, Тест повторно отображается в map (). Я получаю результат после первого выполнения map (). Но тогда this.props.tests получит пустой массив. Как мне обработать onClick, чтобы родительский элемент не перерисовывал все дочерние компоненты?

1 Ответ

0 голосов
/ 03 августа 2020

Я забыл добавить bind () к моему методу getItem :

onClick={this.props.getItem.bind(this, this.props.item.id)}

Работает.

...