我才刚开始玩反应/还原游戏。我只想输入一些文本,然后点击submit,然后将其传递给另一个组件,它将显示输入的内容。
我知道我可以从A点得到数据到B点,因为如果我使用store.subscribe,我可以访问状态,而且它总是准确的。我正在尝试使用mapStateToProps,但我没有任何运气。
我没有使用mapDispatchToProps,所以这可能是个问题吗?我似乎找不到一个好的简单的例子。mapStateToProps似乎也只在我刷新页面时运行(使用webpack-dev服务器),因为它只在页面加载时记录了一次,以后就不再运行了。
_______________ Input.js _________________
import React from 'react';
import store from '../redux/store';
import { connect } from 'react-redux';
import { addSearchParam } from '../redux/actions';
export default class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
player: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
player: event.target.value
});
}
handleSubmit(event) {
event.preventDefault();
store.dispatch(addSearchParam(this.state.player))
}
render() {
return ( <form onSubmit = {this.handleSubmit} >
<label>
<input type="text" value={this.state.player}
onChange={this.handleChange}/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
_______________ Info.js _________________
import React from 'react';
import store from '../redux/store';
import { connect } from 'react-redux';
class Info extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h2> {this.props.player}</h2>
)
}
}
function mapStateToProps(state) {
console.log("mapStateToPropsInfo: ", state)
return {
player: state.player
}
}
export default connect(mapStateToProps, null)(Info);
_______________ reducers.js _________________
'use strict';
import {
combineReducers
} from 'redux';
const SEARCH_PARAM = 'SEARCH_PARAM';
const searchReducer = (state = '', action) => {
if (action.type === SEARCH_PARAM) {
return action.text;
}
return state;
}
export const reducers = combineReducers({
searchReducer
})
export default reducers;
_______________ actions.js _________________
'use-strict';
export const addSearchParam = input => {
return {
type: 'SEARCH_PARAM',
id: 'player',
text: input
}
}
_______________ index.js _________________
'use-strict';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './js/App';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from './js/redux/reducers'
let store = createStore(reducers)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root')
);
这些似乎是最重要的文件与这个问题,但我可以提供更多,如果必要的话。谢谢你的帮助。希望我只是错过了一些简单的东西。
发布于 2017-11-29 05:34:52
我认为问题在于您已经编写了actions,但从未使用/连接过它。需要在Input.js中使用mapDispatchToProps。
首先在action中导入input.js,如下所示:
import { addSearchParam } from './actions';编写这样的mapDispatchToProps函数:
function mapDispatchToProps(dispatch){
return bindActionCreators({addSearchParam}, dispatch);
}然后,在Input.js中的handleSubmit函数中执行以下操作:
this.props.addSearchParam(this.state.player) 另外,更改Input.js的导出语句以绑定mapDispatchToProps,而不是在去学习时导出类:
export default connect(null, mapDispatchToProps)(Input); https://stackoverflow.com/questions/47544862
复制相似问题