从redux商店设置react-widgets DropdownList的值

时间:2017-03-22 14:03:15

标签: react-redux

我正在尝试将react-widgets DropdownList组件连接到global redux store。 如果从this.state获取,则DropdownList会更改所选值的值。 来自onChange处理程序中的react-widgets文档的示例:

var DropdownList = ReactWidgets.DropdownList
  , colors = ['orange', 'red', 'blue', 'purple'];

var Example = React.createClass({
  getInitialState() {
    return { value: colors[3] };
  },
  render() {
    return (
     <DropdownList
       data={colors}
       value={this.state.value}
       onChange={value => this.setState({ value })}/>)
  } 
});

ReactDOM.render(<Example/>, mountNode);

但我想从全局redux商店my codepen example设置DropdownList值:

const colors = [
   { id: 0, name: 'orange'},
   { id: 1, name: 'purple'},
   { id: 2, name: 'red' },
   { id: 3, name: 'blue' },
   { id: 4, name: 'green' }
];

class App extends React.Component { 

   componentWillMount() {
      this.props.setSelectedColor(colors[1]); // !!! HELP, does not work !!!
   }

   render() {
      return(
         <DropdownList className="form-control form-control-sm"
                  id="color-list"
                  valueField="id"
                  textField="name"
                  data={colors}
                  value={this.props.selectedColor}
                  onChange={(value) => this.props.setSelectedColor(value)}
                  />);
    }
}

const reducers = {
  list: setSelectedColor
};

// global redux state <-> store
const store = createStore(rootReducer);

// connect to global redux store selectedColor
function mapStateToProps (state) {
  return {
    selectedColor: state.selectedColor
  }
}

// connect to global actions (setColor) to redux store
function mapDispatchToProps(dispatch) {
  return {
    setSelectedColor: bindActionCreators(setColor, dispatch)
  }
}

const AppForm = connect(
   mapStateToProps,
   mapDispatchToProps
)(App);

ReactDOM.render(
  <Provider store={store}>
    <AppForm />
  </Provider>,
  document.getElementById('app')
);

在方法componentWillMount()中,我在第二个元素(紫色)中设置初始值列表,但它不起作用!

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我通过reducer&#34; list&#34;:

更正了路径连接状态
const reducers = {
  list: setSelectedColor
};

function mapStateToProps (state) {
  return {
    selectedColor: state.list.selectedColor
  }
}

Hooray,现在it有效!