![](/img/trans.png)
[英]Set local state of component with Redux props given from mapStateToProps()
[英]Print value from props, which is delivered to the component from redux by mapStateToProps
問題:
我無法顯示redux狀態的值,該狀態由mapStateToProps
函數傳遞給組件。
項目結構:
Create-react-app CLi應用程序構建了該項目。 在src /內部,我具有以下代碼結構
必要的代碼:我們正在與之交互的主頁看起來像這樣:
計划在下面發布單擊按鈕的結果。
那么,如何將redux狀態和操作綁定到這兩個組件:Calculator和ResultLine?
讓我展示創建商店的index.js代碼:
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducers from './reducers/';
import App from './components/App';
ReactDOM.render(
<Provider store={createStore(reducers)}>
<App />
</Provider>,
document.getElementById("root")
);
只有三個動作:
import {CALCULATE, ERASE, PUT_SYMBOL} from "./types";
export const putSymbol = (symbol) => {
return {
type: PUT_SYMBOL,
payload: symbol
}
};
export const calculate = () => {
return {
type: CALCULATE
}
};
export const erase = () => {
return {
type: ERASE
}
};
在App.js中,我傳遞了reducers,並將其與那些動作綁定到Calculator組件:
import React, {Component} from 'react';
import Calculator from './Calculator';
import ResultLine from "./ResultLine";
import {calculate, erase, putSymbol} from "../actions/index";
import {connect} from "react-redux";
class App extends Component {
render() {
return (
<div>
<Calculator
onSymbolClick={this.props.onSymbolClick}
onEqualsClick={this.props.onEqualsClick}
onEraseClick={this.props.onEraseClick}/>
<br/>
<ResultLine result={this.props.result}/>
</div>
);
}
}
const mapStateToProps = (state) => {
console.log('mapState', state.calc.line);
return {
result: state.line
}
};
const mapDispatchToProps = {
onSymbolClick: putSymbol,
onEqualsClick: calculate,
onEraseClick: erase
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
那很好。 每當我單擊按鈕時,狀態都會改變,並且會在控制台日志中觀察到它,該事件在mapStateToProps函數中調用。
因此,我希望可以輕松地將結果道具傳遞到Result行,並將其作為參數傳遞給ResultLine
組件。 因此,讓我們看一下該元素:
import React from 'react';
const ResultLine = ({result}) => {
return (
<p>{result}</p>
);
};
export default ResultLine;
而且我看不到結果行中有任何更改。 也許,React / Redux生命周期管理和ResultLine
組件出了點問題,只是狀態變化沒有更新?
mapStateToProps
發生錯誤。
代替:
const mapStateToProps = (state) => {
return {
result: state.line
}
}
請用:
const mapStateToProps = (state) => {
return {
result: state.calc.line // calc was missing here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.