我刚开始玩react / redux。我只想输入一些文本并点击提交,然后将其传递给另一个显示输入内容的组件。
我知道我可以从A点到B点获取数据,因为如果我使用store.subscribe而不是我可以访问状态并且它总是准确的。我试图使用mapStateToProps,但我没有运气。
我没有使用mapDispatchToProps所以这可能是一个问题?我似乎无法找到一个很好的简单例子。 mapStateToProps似乎也只在我刷新页面时运行(使用webpack-dev-server),因为它只在页面加载时记录一次,而不再记录。
_______________ 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')
);
&#13;
这些似乎是与此问题相关的最重要的文件,但如果有必要,我可以提供更多。谢谢你的帮助。希望我只是缺少一些简单的东西。