componentWillReceiveProps 不能检测数据的改变

**//我通过websocket发送了请求,收到了返回的一些数据,但是现在Thumbnail组件收不到数据

阅读 2.7k
2 个回答

那这说明你的connect用的不对,你这个createSelector不太清楚你这个是自己封装的还是第三方插件,单connect这个插件来说,它接受的参数一共有四个,分别是 mapStateToProps , mapDispatchToProps, mergeProps 和 options。其中一般用到前两个差不多了。

mapStateToProps

将 store 中的数据作为 props 绑定到组件上。

const mapStateToProps = (state) => {
  return {
    count: state.count
  }
}

mapDispatchToProps

将 action 作为props 绑定到组件上

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    increase: (...args) => dispatch(actions.increase(...args)),
    decrease: (...args) => dispatch(actions.decrease(...args))
  }
}

你对一下看你是不是传的有问题

import React from 'react';
import {render} from 'react-dom';

import {createStore} from 'redux';
import {Provider, connect} from 'react-redux';
import {createSelector} from 'reselect';

//reducer
const todos = (state = 0, action) => {
    switch (action.type) {
        case 'CLICK':
            return action.num
            break;
        default:
            return state
    }
}
//store
const store = createStore(todos)

class Parent extends React.PureComponent {
    constructor() {
        super()
    }

    render() {
        return <div>
            <button onClick={() => {
                store.dispatch({
                    type: 'CLICK',
                    num: Math.random()
                })
            }}>click</button>
            <Child/>
        </div>
    }
}

class Child1 extends React.PureComponent {
    constructor() {
        super()
    }

    // componentWillReceiveProps(nextProps) {
    //     console.log(nextProps);
    // }

    render() {
        return <div>
            {this.props.data}
        </div>
    }
}
const Child = connect(
//mapStateToProps
createSelector((state) => state, (state) => {
    return {data: state}
}),
//mapDispatchToProps
null
)(Child1);

render(
    <Provider store={store}><Parent/></Provider>, document.querySelector('#root'));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题