My dice roll app rolls the dice and logs the previous rolls.
You can see the app on github pages: https://mtrussell.github.io/dice-roll-app/
To see all the app's code, here is the repo: https://github.com/mtrussell/dice-roll-app
The RollDice component adds the current roll to the rolls array. The PrevRolls component reverses the array and maps it to the jsx elements.
The problem is that when I deployed it to github pages it behaves differently than on my local machine. It seems to alter the array after a second, flipping it back around.
I thought that it had something to do with the button timeout, but I removed that completely and the wonky behavior persisted.
I have tried restructuring my code in a number of different ways, but nothing seems to fix it.
RollDice Component -
import React, { Component } from 'react';
import Die from './Die';
import PrevRolls from './PrevRolls';
import './RollDice.css';
class RollDice extends Component {
static defaultProps = {
sides: ['one', 'two', 'three', 'four', 'five', 'six']
}
constructor(props) {
super(props);
this.state = {
die1: 'one',
die2: 'two',
rolling: false,
rolls: []
}
this.handleClick = this.handleClick.bind(this);
}
randomDice() {
const newDie1 = this.props.sides[
Math.floor(Math.random() * this.props.sides.length)
];
const newDie2 = this.props.sides[
Math.floor(Math.random() * this.props.sides.length)
];
return [newDie1, newDie2];
}
roll(dice) {
this.setState(prevState => {
return {
die1: dice[0],
die2: dice[1],
rolling: true,
rolls: [...prevState.rolls, {first: dice[0], second: dice[1]}]
}
});
}
handleClick() {
const dice = this.randomDice();
this.roll(dice);
setTimeout(() => {
this.setState({
rolling: false,
});
}, 1000);
}
render() {
let rollButton = this.state.rolling ? 'Rolling...' : 'Roll Dice!';
return(
<div className='RollDice'>
<div className='RollDice-dice'>
<Die face={this.state.die1} rolling={this.state.rolling} />
<Die face={this.state.die2} rolling={this.state.rolling} />
</div>
<button onClick={this.handleClick} disabled={this.state.rolling}>{rollButton}</button>
<PrevRolls rolls={this.state.rolls} />
</div>
);
}
}
export default RollDice;
PrevRolls Component -
import React, { Component } from 'react';
import './PrevRolls.css'
class PrevRolls extends Component {
constructor() {
super();
this.displayRolls = this.displayRolls.bind(this);
}
reverseRolls() {
return this.props.rolls.reverse();
}
displayRolls() {
return this.reverseRolls().map((roll, index) => (
<p>
Roll {this.props.rolls.length - index} <i className={`fas fa-dice-${roll.first}`} ></i> <i className={`fas fa-dice-${roll.second}`} ></i>
</p>
));
}
render() {
return(
<div className='PrevRolls'>
<div className='PrevRolls-list'>
{this.displayRolls()}
</div>
</div>
);
}
}
export default PrevRolls;
Thanks to xadm, I got this figured out. reverse() was altering the parent component's array.
I changed the way I was setting the state in the roll() function in the RollDice component.
In the PrevRolls component I removed the reverseRolls() function and its function call in the displayRolls() function.
RollDice Component -
roll(dice) {
this.setState(prevState => {
return {
die1: dice[0],
die2: dice[1],
rolling: true,
rolls: [{first: dice[0], second: dice[1]}, ...prevState.rolls]
}
});
}
PrevRolls Component -
displayRolls() {
return this.props.rolls.map((roll, index) => (
<p>
Roll {this.props.rolls.length - index} <i className={`fas fa-dice-${roll.first}`} ></i> <i className={`fas fa-dice-${roll.second}`} ></i>
</p>
));
}
Related
I just started to learn React. I'm trying to write a Todo list and so far it looks like:
However when I check the box of a Todo, the count of things left to do won't change even when the state of a list of Todos changes (the 'checked' property of a Todo that I just checked change to true)
My App.js:
import React, {Component} from 'react';
import TaskComponent from "./TaskComponent";
class App extends Component {
constructor(props) {
super(props)
this.state = {
taskList: [],
newTaskContent: ''
}
this.generateTask = this.generateTask.bind(this)
this.updateNewTaskContent = this.updateNewTaskContent.bind(this)
}
generateTask() {
if (this.state.newTaskContent) {
const joined = this.state.taskList.concat({
id: this.state.taskList.length + 1,
content: this.state.newTaskContent,
checked: false
})
this.setState({taskList: joined, newTaskContent: ''})
}
}
updateNewTaskContent({target: {value}}) {
this.setState({newTaskContent: value})
}
render() {
return (
<div>
<ul>{this.state.taskList.map(task => <TaskComponent key={task.id} task={task.content}
checked={task.checked}/>)}</ul>
<input type='text' placeholder='Type your new task'
onChange={this.updateNewTaskContent} value={this.state.newTaskContent}/>
<button name='generateTask' onClick={this.generateTask}>Generate task</button>
<div>There are {this.state.taskList.filter(task => !task.checked).length} things left to do!</div>
</div>
);
}
}
export default App;
My TaskComponent.js file:
import React, {Component} from 'react'
class TaskComponent extends Component {
constructor({task, checked}) {
super(undefined)
this.state = {
taskContent: task,
checkedState: checked
}
this.changeHandler = this.changeHandler.bind(this)
}
changeHandler({target: {checked}}) {
this.setState({checkedState: checked})
}
render() {
return (
<div>
<span>{this.state.taskContent}</span>
<input type="checkbox" checked={this.state.checkedState} onChange={this.changeHandler}/>
</div>
);
}
}
export default TaskComponent;
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
taskList: [],
newTaskContent: ''
}
this.generateTask = this.generateTask.bind(this)
this.updateNewTaskContent = this.updateNewTaskContent.bind(this)
}
generateTask() {
if (this.state.newTaskContent) {
const joined = this.state.taskList.concat({
id: this.state.taskList.length + 1,
content: this.state.newTaskContent,
checked: false
})
this.setState({taskList: joined, newTaskContent: ''})
}
}
updateNewTaskContent({target: {value}}) {
this.setState({newTaskContent: value})
}
render() {
return (
<div>
<ul>{this.state.taskList.map(task => <TaskComponent key={task.id} task={task.content}
checked={task.checked}/>)}</ul>
<input type='text' placeholder='Type your new task'
onChange={this.updateNewTaskContent} value={this.state.newTaskContent}/>
<button name='generateTask' onClick={this.generateTask}>Generate task</button>
<div>There are {this.state.taskList.filter(task => !task.checked).length} things left to do!</div>
</div>
);
}
}
class TaskComponent extends React.Component {
constructor({task, checked}) {
super(undefined)
this.state = {
taskContent: task,
checkedState: checked
}
this.changeHandler = this.changeHandler.bind(this)
}
changeHandler({target: {checked}}) {
this.setState({checkedState: checked})
}
render() {
return (
<div>
<span>{this.state.taskContent}</span>
<input type="checkbox" checked={this.state.checkedState} onChange={this.changeHandler}/>
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector("#root"));
<script src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Inside the TaskComponent class I add the function for the event of changing the "checked" state of the check box but somehow the 'taskList' state in my App does not change at all when I try to console.log it. What is my problem here? Be gentle since I'm new to React and Javascript in general.
You are setting state in TaskComponent and expecting it to change the prop in App.js.
Instead of setting a TaskComponents's state when it is checked, I would recommend calling a function passed in as a prop when it is checked, which has its id and new value. Something along the lines of:
App.js:
// somewhere in your class:
handler(id, value) {
// set state to reflect changes
}
// in your render()
<ul>{this.state.taskList.map((task) => {
<TaskComponent onChange={this.handler} id={task.id} key={task.id} task={task.content} checked={task.checked} />})}</ul>
In TaskComponent.js:
changeHandler({target: {checked}}) {
this.props.onChange(this.props.id, checked);
}
I would also recommend making TaskComponent not have state at all, because it seems unnecessary to me.
Good evening,
as a learning project I want to build a simple "Learning Cards" App. The structure is quite simple: you have cards with questions. After a button click, you can show the correct solution. You can also click on "Question solved" to move the learning card to the absolved cards.
I am struggling to realize the "moving the learning card to the absolved" cards part. I have a "questions" array. After "onSolvedClick" the solved card gets copied to the "solved" array which is set as the new solved state.
When I click on the "Frage gelöst" (question solved) button, a new card appears in the solved questions region. The problem is: the new card is empty (without the question / answer). It would be great if someone could help me at this point! I already spent hours on this problem today.
I guess my mistake is within the App.Js code, probably in "onSolvedKlick" or "solveFragen".
Thanks a lot!
App.Js:
import React, {Component} from 'react';
import CardList from './CardList.js';
import { fragen } from './fragen';
import SearchBox from './SearchBox';
class App extends Component { // As Class to access objects
constructor () {
super();
this.state = { // State needed to change state
fragen: fragen,
solved : [] ,
searchfield: ''
}
}
onSearchChange = (event) => {
this.setState({searchfield: event.target.value});
}
onSolvedKlick = (id) => {
console.log("Klick on solved"+id);
var frage = this.state.fragen.filter(function(e) // Bei Klick auf Solved: filtere aus Ursprungsarray das Element mit gelöster iD
{
return e.id === id;
});
console.log(frage);
const newSolvedArray = this.state.solved.slice();
newSolvedArray.push(frage);
this.setState({solved: newSolvedArray});
}
render(){ // DOM rendering
const filteredFragen = this.state.fragen.filter(fragen =>{
return fragen.frage.toLowerCase().includes(this.state.searchfield.toLowerCase());
})
const solveFragen = this.state.solved;
return(
<div className='tc'>
<h1>Learning Cards</h1>
<SearchBox searchChange={this.onSearchChange}/>
<h2>Cards: To be learned!</h2>
<div>
<CardList fragen={filteredFragen} onSolvedKlick={this.onSolvedKlick}/>
<CardList fragen={solveFragen} onSolvedKlick={this.onSolvedKlick}/>
</div>
</div>
)
}
}
export default App;
CardList.js:
import React from 'react';
import Card from './Card';
const CardList = ({fragen, onSolvedKlick}) => {
const cardComponent = fragen.map( (user, i) => {
return(<Card key={i} id={fragen[i].id} frage = {fragen[i].frage} antwort = { fragen[i].antwort} onSolvedKlick = {onSolvedKlick}/>);
}
)
return (
<div>
{cardComponent}
</div>
);
}
export default CardList;
Card.js:
import React, {Component} from 'react';
import 'tachyons';
class Card extends Component {
constructor(props) {
super(props);
this.state = {
frage : props.frage,
showAnswer : false
};
}
_showAnswer = () => {
const before = this.state.showAnswer;
const after = !before;
this.setState({
showAnswer: after
});
}
render() {
return (
<div className ="fl w-50 w-25-m w-20-l pa2 bg-light-red ma3">
<div>
<h2>{this.props.frage}</h2>
{ this.state.showAnswer && (<div>{this.props.antwort}</div>) }
<p></p>
<input type="button" value="Antwort anzeigen" className ="ma2"
onClick={this._showAnswer.bind(null)}
/>
<input type="button" name="solved" value="Frage gelöst" className = "ma2 bg-light-green"
onClick={() =>this.props.onSolvedKlick(this.props.id)}
/>
</div>
</div>
);
}
}
fragen.js (Questions):
export const fragen = [
{
id: 1,
frage: 'What are trends in CPU design?',
antwort: 'Multi-core processors, SIMD support, Combination of core private and shared caches Heterogeneity, Hardware support for energy control',
topic: 'Cloud'
},
{
id: 2,
frage: 'What is typical for multi-core processors?',
antwort: 'Cache Architecture (L1 private to core, L2 private to tile), Cache Coherence',
topic: 'Cloud'
},
{
id: 3,
frage: 'What memory modes exist?',
antwort: 'Flat mode, Cache Mode, Hybrid Mode',
topic: 'Cloud'
},
{
id: 4,
frage: 'What memory modes exist?',
antwort: 'Flat mode, Cache Mode, Hybrid Mode',
topic: 'Cloud'
},
];
Try this on your onSolvedKlick function:
onSolvedKlick = (id) => {
console.log("Klick on solved"+id);
var frage = this.state.fragen.filter((e) => e.id === id);
this.setState({solved: [...this.state.solved, frage]});
}
Try to avoid so many empty lines.
Also keep your code always in english so it's easier for others to understand. I had the luck to be german too :)
Assuming that you want to move the questions from fragen array to solved array, here is how to do that.
onSolvedKlick = id => {
console.log("Klick on solved" + id);
var elementPos = this.state.fragen.map(function(x) {return x.id; }).indexOf(id); // Find the position of the selected item in the fragen
const currentItem = this.state.fragen.splice(elementPos,1)
const newSolvedArray = this.state.solved;
newSolvedArray.push(currentItem[0]);//splice gives an array
this.setState({ solved: newSolvedArray }, function() {console.log(this.state)});
};
I have a very basic ReactJS app which uses Redux which contains the following components:
PanelMaterialSize > Select
/src/controls/PanelMaterialSize/PanelMaterialSize.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './PanelMaterialSize.scss';
import Select from '../Select/Select';
import { setThemeList } from '../../store/AppConfig/actions';
class PanelMaterialSize extends Component {
componentDidMount() {
this.n = 1;
setInterval(() => {
let themeList = [
{ value: this.n, text: 'Option ' + this.n },
{ value: this.n + 1, text: 'Option ' + (this.n + 1) },
{ value: this.n + 2, text: 'Option ' + (this.n + 2) },
];
this.props.setThemeList(themeList);
this.n += 3;
}, 1000);
}
render() {
return (
<div className="partial-designer-panel-material-size">
<div>
<div className="label-input">
<div className="label">MATERIAL</div>
<div className="input">
<Select data={this.props.themeList} style={{ width: '100%' }} />
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (appState) => {
return {
themeList: appState.appConfig.themeList,
}
}
const mapDispatchToProps = (dispatch) => {
return {
setThemeList: (themeList) => dispatch(setThemeList(themeList)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(PanelMaterialSize);
In my opinion the Redux logic is fine because I have tested by doing couple of things.
My problem is that when the render(...) method of: PanelMaterialSize gets called, the component: Select doesn't get rendered with the new data (which changes every one second).
Here you have a Codesandbox.io you can play with (preferable use Chrome):
https://codesandbox.io/s/03mj405zzv
Any idea on how to get its content changed properly?
If possible, please, provide back a new Codesandbox.io with your solution, forked from the previous one.
Thanks!
the problem is here in your select component.
you are passing initially empty array and checking your component with this.state.data props, next time reducer change your this.state.data will not update the data. because you initialize in constructor. constructor only invoke once when component mount.
SOLVED DEMO LINK
The Problem is in your select render method:
render() {
let data = this.state[this.name];
return (
<div className="control-select" {...this.controlProps}>
<div className="custom-dropdown custom-dropdown--grey">
<select className="custom-dropdown__select custom-dropdown__select--grey">
//change data with this.props.data
{this.props.data.length > 0 &&
this.props.data.map((elem, index) => {
return (
<option value={elem.value} key={index}>
{elem.text}
</option>
);
})}
</select>
</div>
</div>
);
}
I'm struggling to pose this question in a concise manner. I am having some major performance issues with my app. I have installed the Perf add-on tools for react and can see where the issue is, however I am unsure of the best way to fix it.
I think it will probably have something to do with ReSelect... but need some guidance on where to begin.
I have a component that renders a number of other components. This uses size-me (to calculate the size of the browsing window), and react-grid-layout (to layout each component and permit their positioning to be changed). This is resource intensive, so I can't have this happening unnecessarily.
The user can click on a button to open a modal window (to add or edit the components that are being rendered in the grid).
The issue: When the modal window opens, the underlying component re-renders, causing size-me and react-grid-layout to re-render, which thus causes the modal to "jerkingly" open!
This is the entire state tree:
This is the only part of the state that changes when I open the modal:
The size-me and react-grid-layout stuff is rendering state from the formEngine.form part of the state tree, yet it is being re-rendered when state updates are made to the formEngine.addComponent part of the tree
Here are the performance logs:
As you can see, there are some wasted renders happening AND this will only grow incrementally based on the number of nested layout components the user decides to add to the form...
So to try and prevent this question from becoming too convoluted, let me ask first:
How do I prevent the underlying page from re-rendering when I open the modal?
Why are components that are watching formEngine.form triggered to re-render when fromEngine.addComponent gets modified?
Thank you.
EDIT 1:
I'm not sure if this is relevant, but to answer the comment, I added this code. The AddFormComponent is the Modal that jerks open.
Form.js:
const Form = (props) => (
<div className="form-engine">
<div className="card-block" style={{position: "relative"}}>
{
props.editMode &&
<div className="nula-form-controls">
<AddFormComponent parentId={"root"} />
</div>
}
{
props.form.components.root.childComponentIds.length > 0 ?
<LayoutComponent componentKey={"root"} />
:
<EmptyGridLayout />
}
</div>
</div>
)
LayoutComponent.js:
import React from 'react'
import _ from 'lodash'
import SizeMe from 'react-sizeme'
import { Responsive as ResponsiveReactGridLayout } from 'react-grid-layout'
import 'react-grid-layout/css/styles.css'
import 'react-resizable/css/styles.css'
import FormComponent from '../containers/FormComponent'
import NestedLayoutComponent from '../containers/LayoutComponent'
import AddFormComponent from '../containers/AddFormComponent'
import LayoutComponentEditor from '../containers/LayoutComponentEditor'
//Setup SizeMe Configuration
let sizeMeConfig = {
monitorWidth: true
}
let sizeMeHOC = SizeMe(sizeMeConfig)
//Wrap ResponsiveReactGridLayout in sizeMeHOC so that it is aware of it's width
var GridLayout = ResponsiveReactGridLayout
GridLayout = sizeMeHOC(GridLayout)
const LayoutComponent = (props) => (
<div>
<GridLayout
cols={props.cols}
className={props.className}
breakpoints={props.breakpoints}
rowHeight={props.rowHeight}
draggableCancel={props.draggableCancel}
layouts={props.layouts}
isDraggable={props.isDraggable}
isResizable={props.isResizable}
onLayoutChange={(currentLayout, allLayouts) => props.handleLayoutChange(props.componentKey, currentLayout, allLayouts)}
width={props.size.width}
>
{
//Map out any child layouts
props.childComponents.map((component) => {
if (component.type === "card") {
return (
<div className={"card card-outline-" + component.color} key={component.key}>
<div className={"card-header card-" + component.color}>
{component.header}
</div>
<div className="card-block" style={{overflowY: "auto", position: "relative"}}>
{
//Hide if editMode={false}
props.editMode &&
<div className="nula-card-controls">
<LayoutComponentEditor path={component.key} />
<span className="fa fa-trash" />
<AddFormComponent parentId={component.key} />
</div>
}
<NestedLayoutComponent componentKey={component.key} />
</div>
</div>
)
}
else if (component.type === "fieldGroup") {
return (
<div className="card" key={component.key}>
<div className="card-block pl-0 pr-0 pt-2 pb-0" style={{overflowY: "auto"}}>
{
//Hide if editMode={false}
props.editMode &&
<div className="nula-fieldgroup-controls">
<a className="text-warning" title="Edit"><span className="fa fa-pencil" /></a>
<a className="text-danger" title="Remove"><span className="fa fa-trash" /></a>
<AddFormComponent parentId={component.key} />
</div>
}
<NestedLayoutComponent componentKey={component.key} />
</div>
</div>
)
}
else if (component.type === "paragraph") {
return (
<div className="alert alert-success text-font-bold" key={component.key}>
{
<FormComponent component={component} editMode={props.editMode} />
}
</div>
)
}
else {
return (
<div key={component.key}>
{
<FormComponent component={component} editMode={props.editMode} />
}
</div>
)
}
})
}
</GridLayout>
</div>
)
export default SizeMe()(LayoutComponent)
EDIT 2:
AddFormComponent.js -- Component
import React from 'react'
import AddFormComponentDetails from './AddFormComponentDetails'
import Perf from 'react-addons-perf'; // ES6
class AddFormComponent extends React.Component {
constructor(props) {
super(props);
this.localOpenModal = this.localOpenModal.bind(this);
}
localOpenModal() {
console.log("----STARTING PERFORMANCE MONITOR-----")
Perf.start()
this.props.handleOpenModal();
}
componentDidUpdate() {
console.log("-----PERFORMANCE MONITOR STOPPING------")
Perf.stop()
console.log("-----PRINT INCLUSIVE------")
Perf.printInclusive()
console.log("-----PRINT WASTEED------")
Perf.printWasted()
}
render() {
return (
<span>
<a onTouchTap={this.localOpenModal} className="text-success" title="Add Component">
<span className="fa fa-plus" />
</a>
<Modal isOpen={this.props.modalOpen} size={"lgr"} toggle={this.props.handleCloseModal}>
<ModalHeader toggle={this.props.handleCloseModal}>Add Component</ModalHeader>
<ModalBody>
...Removed For Breviety
</ModalBody>
<ModalFooter>
...Removed For Breviety
</ModalFooter>
</Modal>
</span>
)
}
}
export default AddFormComponent
AddFormComponent.js -- Container
import { connect } from 'react-redux'
import {
handleOpenModal,
handleCloseModal,
handleGoBack,
handleComponentPropertyChange,
handleComponentNameChange,
handleComponentTypeChange,
handleSubmit
} from '../actions/addFormComponentActions'
import AddFormComponent from '../components/AddFormComponent'
const mapStateToProps = (state) => ({
steps: [
{ icon: 'superpowers', title: 'Select Component', description: 'Select the Component you wish to add', active: state.addComponent.currentStep == 1 },
{ icon: 'info circle', title: 'Enter Details', description: 'Enter details to customize component', active: state.addComponent.currentStep == 2 },
{ icon: 'check', title: 'Add Component', description: 'Add component to form' }
],
currentStep: state.addComponent.currentStep,
modalOpen: state.addComponent.modalOpen,
component: state.addComponent.component,
errors: state.addComponent.errors,
componentType: state.addComponent.componentType
})
export default connect(
mapStateToProps,
{
handleOpenModal,
handleCloseModal,
handleGoBack,
handleComponentPropertyChange,
handleComponentNameChange,
handleComponentTypeChange,
handleSubmit
}
)(AddFormComponent)
addFormComponentReducer.js
import _ from 'lodash'
import {
ADD_FORM_COMPONENT_TOGGLE_MODAL,
ADD_FORM_COMPONENT_CLOSE_MODAL,
ADD_FORM_COMPONENT_GO_BACK,
ADD_FORM_COMPONENT_SUBMIT,
ADD_FORM_COMPONENT_PROPERTY_CHANGE,
ADD_FORM_COMPONENT_PROPERTY_ERROR,
ADD_FORM_COMPONENT_KEY_ERROR,
ADD_FORM_COMPONENT_NAME_CHANGE,
ADD_FORM_COMPONENT_NAME_ERROR,
ADD_FORM_COMPONENT_TYPE_CHANGE,
ADD_FORM_COMPONENT_TYPE_ERROR
} from '../actions/addFormComponentActions'
let initialState = {
currentStep: 1,
modalOpen: false,
component: {
key: '',
label: '',
headingText: '',
text: ''
},
errors: {
key: {
hasError: false,
msg: ''
},
label: {
hasError: false,
msg: ''
},
text: {
hasError: false,
msg: ''
}
}
}
function addFormComponentReducer(state = initialState, action) {
switch (action.type) {
case ADD_FORM_COMPONENT_TOGGLE_MODAL:
return {
...state,
modalOpen: action.payload.isOpen,
currentStep: 1
}
case ADD_FORM_COMPONENT_CLOSE_MODAL:
return initialState;
case ADD_FORM_COMPONENT_GO_BACK:
return {
...state,
currentStep: 1
}
case ADD_FORM_COMPONENT_SUBMIT:
return initialState;
case ADD_FORM_COMPONENT_PROPERTY_CHANGE:
return {
...state,
component: {
...state.component,
[action.payload.key]: action.payload.value
}
}
case ADD_FORM_COMPONENT_PROPERTY_ERROR:
return {
...state,
errors: {
...state.errors,
[action.payload.key]: {
hasError: action.payload.hasError,
msg: action.payload.msg
}
}
}
case ADD_FORM_COMPONENT_TYPE_CHANGE:
return {
...state,
componentType: action.payload.componentType,
currentStep: 2
}
default:
return state
}
}
export default addFormComponentReducer
index.js -- Combine Reducers
import { combineReducers } from 'redux'
//import FormEngine reducers
import formReducer from './formReducer'
//import addFormComponentReducer from './addFormComponentReducer'
import componentEditorReducer from './componentEditorReducer'
const rootFormEngineReducer = combineReducers({
form: formReducer,
//addComponent: addFormComponentReducer,
componentEditor: componentEditorReducer
})
export default rootFormEngineReducer
rootReducer.js
import { combineReducers } from 'redux'
//import reducers
import rootCoreLayoutReducer from '../features/CoreLayout/reducers'
import rootFormEngineReducer from '../features/FormEngine/reducers'
import addComponentReducer from '../features/FormEngine/reducers/addFormComponentReducer'
const rootReducer = combineReducers({
coreLayout: rootCoreLayoutReducer,
formEngine: rootFormEngineReducer,
addComponent: addComponentReducer
})
export default rootReducer
If you are using a pure component any performance optimizations have to be handled manually(using shouldComponentUpdate). Since you are using redux it can handle that for you. But you have to "connect" it to the redux store.
If you choose to use redux connect ensure that the modal visibility is not related to your other properties specifically in your case:
modalOpen is nested in formEngine. When it changes anything else that listens to formEngine will rerender
I have a react code where I have onClicke event. I suppose to get implementation of function(someFunction). I didn't get any error running this code, everything else works. I guess the problem can be in function. The React code is
class Hello extends Component {
constructor() {
super();
this.num = { number: 4 };
this.someFunction = this.someFunction.bind(this);
}
someFunction() { this.setState({ number: this.num.number + 3 }); }
render() {
const coco = {
color: 'blue',
background: 'yellow',
width: '200px',
height: '200px',
padding: 'lem'
};
return (<div style={coco} onClick={this.someFunction}>
<p style={coco} onClick={this.someFunction}> bly blya
Hello {this.props.name} </p>
<p style={coco} onClick={this.someFunction} >
Current count: {this.num.number + 3}
</p>
</div>)
}
}
render(<Hello/>, document.getElementById('container'));
actually it is working just fine , your component isn't updating because it doesn't depend on state in fact you havne't defined any state in the constructor which might be a typo ..
import React , {Component} from 'react'
import ReactDOM from 'react-dom'
class Hello extends Component {
constructor() {
super();
// defining state
this.state = { number: 4 };
this.someFunction = this.someFunction.bind(this);
}
someFunction() {
//chnaging state case re-render for component
this.setState({number: this.state.number + 3 });
}
render() {
const coco = {
color: 'blue',
background: 'yellow',
width: '200px',
height: '200px',
padding: 'lem'
};
return (
<div style={coco} onClick={this.someFunction}>
<p style={coco} onClick={this.someFunction}> bly blya
Hello {this.props.name} </p>
<p style={coco} onClick={this.someFunction} >
Current count: {this.state.number + 3 /*need to use state here . */}
</p>
</div>
)
}
}
ReactDOM.render(<Hello/>, document.getElementById('container'));
You should replace:
Current count: {this.num.number + 3}
with:
Current count: {this.state.num.number + 3}
Instead of defining this.num, you should define the initial state of your component in the constructor:
this.state = {
number: 4,
};
Your function gets correctly called on the click callback, however the logic of updating the state doesn't work because it always returns the same state. this.num.number always has a value of 4 and thus your state will always have a value of 7 after calling setState.
You can use the previous state to calculate the new state like this:
this.setState((prevState) => {
return {
number: prevState.number + 3
};
});
See this JSFiddle