简体   繁体   English

React redux 道具不更新

[英]React redux props don't update

I'm using Redux with React, and I expect my props to update whenever the store changes, but they don't.我正在将 Redux 与 React 一起使用,我希望我的 props 在商店发生变化时更新,但他们没有。

I omitted all imports and left only the code related to the problem我省略了所有导入,只留下了与问题相关的代码

function TableBody({ rows, rowsPerPage, page }) {

    useEffect(() => {
        console.log('chagned'); //only get's triggered on initial render
        console.log(rows);
    }, [rows])

    return (
        <TableBodyMaterial>
            {console.log(rows, rows[0])}
            {console.log(rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage))}
            {rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map(row => {
                console.log(row);
                return (
                    <TableRow row={row} key={row.email} />
                );
            })}
        </TableBodyMaterial>
    )
}

const mapStateToProps = (state, ownProps) => {
    console.log(state.rows);  // logs rows on every store change
    return {
        rows: state.rows
    }
}

export default connect(
    mapStateToProps
)(TableBody);

reducer.js减速器.js

const initialState = {
    rows: getData()
}

function rootReducer(state = initialState, action) {
    switch (action.type) {
        case SORT: {
            const { by, direction } = action.payload;
            const newRows = state.rows.sort((a, b) => {
                if (typeof a[by] === 'string') {
                    return a[by].localeCompare(b[by]);
                }
                return a[by] - b[by];
            });
            console.log(newRows);
            return { rows: newRows }
        }
        default: return state
    }
}

export default rootReducer;

mapStateToProps function is being called, but props never seem to change, what am I doing wrong?正在调用mapStateToProps函数,但道具似乎从未改变,我做错了什么?

You are not updating the reference rows array.您没有更新参考rows数组。 You need to assign a new reference to rows您需要为rows分配一个新的引用

case SORT: {
   const { by, direction } = action.payload;
   const newRows = state.rows.sort((a, b) => {
      if (typeof a[by] === 'string') {
        return a[by].localeCompare(b[by]);
      }
      return a[by] - b[by];
   });
   return { rows: [...newRows] }; //need to do like this
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM